Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post file to ASP.NET Web Api 2

I'd like to post a file to my webapi. It's not the problem but:

  1. I don't want to use javascript
  2. The file must be received and saved synchronously
  3. I would like my action to look like this:

    public void Post(byte[] file)
    {
    
    }
    

    or:

    public void Post(Stream stream)
    {
    
    }
    
  4. I want to post file from code similiar to this (of course, now it doesn't work):

    <form id="postFile" enctype="multipart/form-data" method="post">
    
        <input type="file" name="file" />
    
        <button value="post" type="submit" form="postFile"  formmethod="post" formaction="<%= Url.RouteUrl("WebApi", new { @httpRoute = "" }) %>" />
    
    </form>
    

Any suggestions will be appreciated

like image 692
Fuffu Avatar asked Oct 28 '15 09:10

Fuffu


People also ask

How do I upload files to IFormFile?

Upload Single FileTo add view, right click on action method and click on add view. Then select View from left side filter and select Razor View – Empty. Then click on Add button. Create design for your view as per your requirements.

How do I upload a file using .NET core API?

To upload a single file using . NET CORE Web API, use IFormFile which Represents a file sent with the HttpRequest. This is how a controller method looks like which accepts a single file as a parameter.


1 Answers

The simplest example would be something like this

[HttpPost]
[Route("")]
public async Task<HttpResponseMessage> Post()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    var provider = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/App_Data"));

    var files = await Request.Content.ReadAsMultipartAsync(provider);

    // Do something with the files if required, like saving in the DB the paths or whatever
    await DoStuff(files);

    return Request.CreateResponse(HttpStatusCode.OK);;
}

There is no synchronous version of ReadAsMultipartAsync so you are better off playing along.

UPDATE:

If you are using IIS server hosting, you can try the traditional way:

public HttpResponseMessage Post()
{
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count > 0)
    {
        foreach (string fileName in httpRequest.Files.Keys)
        {
            var file = httpRequest.Files[fileName];
            var filePath = HttpContext.Current.Server.MapPath("~/" + file.FileName);
            file.SaveAs(filePath);
        }

        return Request.CreateResponse(HttpStatusCode.Created);
    }

    return Request.CreateResponse(HttpStatusCode.BadRequest);
}
like image 62
vtortola Avatar answered Sep 22 '22 01:09

vtortola