Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 294
user877247 Avatar asked Dec 14 '25 02:12

user877247


1 Answers

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);
    }
}
like image 174
Rob Davis Avatar answered Dec 16 '25 20:12

Rob Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!