如何将文件发布到ASP.NET Web Api 2

时间:2015-10-28 09:50:39

标签: asp.net asp.net-web-api

我想将文件发布到我的webapi。这不是问题,但是:

  1. 想要使用javascript
  2. 必须接收并保存同步
  3. 我希望我的行动看起来像这样:

    public void Post(byte[] file)
    {
    
    }
    

    或:

    public void Post(Stream stream)
    {
    
    }
    
  4. 我想从类似的代码发布文件(当然,现在它不起作用):

    <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>
    
  5. 任何建议都将受到赞赏

2 个答案:

答案 0 :(得分:9)

最简单的例子就是这样的

[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);;
}

ReadAsMultipartAsync没有同步版本,所以你最好还是一起玩。

<强>更新

如果您使用的是IIS服务器托管,可以尝试传统方式:

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);
}

答案 1 :(得分:-2)

我认为行动应该像

[HttpPost]
    public ActionResult post(HttpPostedFileBase file)
    {
        // Verify that the user selected a file
        if (file != null && file.ContentLength > 0) 
        {
            // extract only the filename
            var fileName = Path.GetFileName(file.FileName);
            // store the file inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }
        // redirect back to the index action to show the form once again
        return RedirectToAction("Index");        
    }