1

I'm using VS2015 to create a WebApi project. Specifically, I'm trying to write a simple web service to upload files using POST.

I have done this before using previous versions of Visual Studio, but VS2015 utilizes ASP.NET 5 and MVC 6 which apparently has some major api changes.

Before, I could use something like this:

Request.Content.ReadAsMultipartAsync().Result.Contents

BTW, this is what every site I googled recommends. But my copy of VS2015 gives me the following compile time error message:

'HttpContent does not contain a definition for ReadAsMultipartAsync'

The overall project structure for WebApi's seem to be revamped in VS2015. At this point I have no idea what's wrong (whether it's a code issue or a VS2015 issue). I've spent the last couple of days trying to get this resolved. Can anyone provide insight as to what I'm doing wrong?

Below is my controller in it's entirety:

    [Route("api/[controller]")]
public class UploadController : Controller
{
    private readonly IApplicationEnvironment appEnvironment;

    public UploadController(IApplicationEnvironment appEnvironment)
    {
        this.appEnvironment = appEnvironment;
    }

    // POST api/values
    [HttpPost]
    public void Post(HttpRequestMessage request)
    {
        string logFolder = "logs";
        string fileName = "uploader.log";
        string logFile = Path.Combine(this.appEnvironment.ApplicationBasePath, logFolder, fileName);
        string directory = Path.GetDirectoryName(logFile);

        if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }

        using (Stream requestStream = GetStreamFromUploadedFile(request))
        {
            using (Stream fileStream = System.IO.File.Create(logFile))
            {
                try
                {
                    requestStream.CopyTo(fileStream);
                }
                finally
                {
                    // No longer supported?
                    //fileStream.Close();
                    //requestStream.Close();
                }
            }
        }

    }

    private static Stream GetStreamFromUploadedFile(HttpRequestMessage request)
    {
        IEnumerable<HttpContent> parts = null;
        Task.Factory
            .StartNew(() => parts = request.Content.ReadAsMultipartAsync().Result.Contents,
                            CancellationToken.None,
                            TaskCreationOptions.LongRunning,
                            TaskScheduler.Default)
            .Wait();

        Stream stream = null;
        Task.Factory
            .StartNew(() => stream = parts.First().ReadAsStreamAsync().Result,
                            CancellationToken.None,
                            TaskCreationOptions.LongRunning,
                            TaskScheduler.Default)
            .Wait();
        return stream;
    }
}
2
  • 1
    ASP.NET 5 is still in beta. Keep that in mind, and a lot of stuff have been moved around. If you're not comfortable with that, you may want to not use ASP.NET 5 just yet. Simply googling things is probably going to find advice for older versions of ASP.NET, and won't be that useful unless you learn where to look. Since ASP.NET 5 is developed in the open on GitHub, you're welcome to look at the source there.
    – mason
    Sep 17, 2015 at 14:20
  • <sigh> Wish I knew this from the beginning. </sigh> Thanks for your response.
    – mrtedweb
    Sep 17, 2015 at 14:57

1 Answer 1

1

Following is an example of how you can do file uploads in ASP.NET 5/MVC 6: https://github.com/aspnet/Mvc/blob/dev/test/WebSites/ModelBindingWebSite/Controllers/FileUploadController.cs#L16

using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Http;
using Microsoft.Net.Http.Headers;
using ModelBindingWebSite.Models;

namespace ModelBindingWebSite.Controllers
{
    public class FileUploadController : Controller
    {
        public FileDetails UploadSingle(IFormFile file)
        {
            FileDetails fileDetails;
            using (var reader = new StreamReader(file.OpenReadStream()))
            {
                var fileContent = reader.ReadToEnd();
                var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
                fileDetails = new FileDetails
                {
                    Filename = parsedContentDisposition.FileName,
                    Content = fileContent
                };
            }

            return fileDetails;
        }

        public FileDetails[] UploadMultiple(IEnumerable<IFormFile> files)
        {
            var fileDetailsList = new List<FileDetails>();
            foreach (var file in files)
            {
                var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
                using (var reader = new StreamReader(file.OpenReadStream()))
                {
                    var fileContent = reader.ReadToEnd();
                    var fileDetails = new FileDetails
                    {
                        Filename = parsedContentDisposition.FileName,
                        Content = fileContent
                    };
                    fileDetailsList.Add(fileDetails);
                }
            }

            return fileDetailsList.ToArray();
        }

        public IDictionary<string, IList<FileDetails>> UploadMultipleList(IEnumerable<IFormFile> filelist1,
                                                                     IEnumerable<IFormFile> filelist2)
        {
            var fileDetailsDict = new Dictionary<string, IList<FileDetails>>
            {
                { "filelist1", new List<FileDetails>() },
                { "filelist2", new List<FileDetails>() }
            };
            var fileDetailsList = new List<FileDetails>();
            foreach (var file in filelist1.Concat(filelist2))
            {
                var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
                using (var reader = new StreamReader(file.OpenReadStream()))
                {
                    var fileContent = reader.ReadToEnd();
                    var fileDetails = new FileDetails
                    {
                        Filename = parsedContentDisposition.FileName,
                        Content = fileContent
                    };
                    fileDetailsDict[parsedContentDisposition.Name].Add(fileDetails);
                }
            }

            return fileDetailsDict;
        }

        public KeyValuePair<string, FileDetails> UploadModelWithFile(Book book)
        {
           var file = book.File;
            var reader = new StreamReader(file.OpenReadStream());
            var fileContent = reader.ReadToEnd();
            var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
            var fileDetails = new FileDetails
            {
                Filename = parsedContentDisposition.FileName,
                Content = fileContent
            };

            return new KeyValuePair<string, FileDetails>(book.Name, fileDetails);
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.