3

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?

user877247
  • 107
  • 1
  • 1
  • 9

1 Answers1

2

This code sample is from a ASP.NET Web API project I did sometime 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);
    }
}
Rob Davis
  • 1,299
  • 1
  • 10
  • 22
  • It does not recognize any file attached to it. It does not go any further than this line above: `if (firstImage == null || firstImage.Headers.ContentDisposition.FileName == null)` This is the form that i am using to post the file: `
    `
    – user877247 Jul 01 '15 at 03:44
  • it worked. i am now caught up with the situation of not being able to capture the fields being passed to me from the form that is defined as multipart/form-data. – user877247 Jul 01 '15 at 15:12
  • @user877247 - great to hear that this answer worked for you. With this solution in place, it should be only a small amount of work to store that byteArray in your database. – Rob Davis Jul 01 '15 at 15:38
  • is there any way to capture form variables from within my post method in apicontroller class? the solutions that i have looked so far are extending default MultipartMemoryStreamProvider behavior. – user877247 Jul 01 '15 at 16:19