asp.netasp.net-mvcasp.net-mvc-4httpasp.net-web-api

File Upload : ApiController


I have a file being uploaded using http post request using multipart/form-data to my class that is extending from ApiController.

In a dummy project, I am able to use:

HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase 

to get the file inside my controller method where my Request is of type System.Web.HttpRequestWrapper.

But inside another production app where I have constraints of not adding any libraries/dlls, I don't see anything inside System.Web.HttpRequestWrapper.

My simple requirement is to get the posted file and convert it to a byte array to be able to store that into a database.

Any thoughts?


Solution

  • This code sample is from an ASP.NET Web API project I did some time ago. It allowed uploading of an image file. I removed parts that were not relevant to your question.

    public async Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    
        try
        {
            var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
    
            var firstImage = provider.Contents.FirstOrDefault();
    
            if (firstImage == null || firstImage.Headers.ContentDisposition.FileName == null)
                return Request.CreateResponse(HttpStatusCode.BadRequest);
    
            using (var ms = new MemoryStream())
            {
                await firstImage.CopyToAsync(ms);
    
                var byteArray = ms.ToArray();
            }
    
            return Request.CreateResponse(HttpStatusCode.Created);
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
        }
    }