Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a httppostedfile from a ASP.NET Web API (POST or PUT) call?

Actually my question is short.

How can I get a HttpPostedFile from a ASP.NET Web API POST or PUT?

I did see that I can get various information from the Request like Request.Header, Request.Content, Request.Properties. Where in there can I find the file I passed and how can I create a HttpPostedFile from it?

Thanks in advance!

like image 272
SwissCoder Avatar asked Dec 21 '22 21:12

SwissCoder


2 Answers

Check out the great article from Henrik Nielsen to post multi-part content (i.e posting a form with file)

UPDATE: Add simple code for a controller to receive a file without multipart content

If you only need your controller to receive a file (i.e. no multipart content), you could do something like the above. The request only contains the file binary and the filename is passed within the URL.

public Task<HttpResponseMessage> Post([FromUri]string filename)
{
    Guid uploadedFile = Guid.NewGuid();
    Task<HttpResponseMessage> task = Request.Content.ReadAsStreamAsync().ContinueWith<HttpResponseMessage>(t =>
         {
            if (t.IsFaulted || t.IsCanceled)
                throw new HttpResponseException(HttpStatusCode.InternalServerError);

            try
            {
                using (Stream stream = t.Result)
                {
                    //TODO: Write the stream to file system / db as you need
                }
            }
            catch (Exception e)
            {
                Object o = e;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, e.GetBaseException().Message);
             }

            return Request.CreateResponse(HttpStatusCode.Created, uploadedFile.ToString());
         });


    return task;
}
like image 123
Julien Jacobs Avatar answered Jan 13 '23 14:01

Julien Jacobs


Your short question does not have a short answer I am afraid.

ASP.NET Web API exposes you to the wonders of HTTP while ASP.NET MVC abstracted some of it - in this case for HttpPostedFile.

So a bit of background:

HTTP posts where a file is involved usually has multipart form data content. This means that you are mixing different kind of content-type: your normal form data will be sent using formurlencoded while the files will be sent application/octent-stream.

So in Web API, all you have to do is to say

var contents = message.Content.ReadAsMultipartAsync(); // message is HttpRequestMessage

One of the contents will contain your file.

like image 31
Aliostad Avatar answered Jan 13 '23 13:01

Aliostad