【问题标题】:How to post file to ASP.NET Web Api 2如何将文件发布到 ASP.NET Web Api 2
【发布时间】:2015-10-28 09:50:38
【问题描述】:

我想将文件发布到我的 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>
    

任何建议将不胜感激

【问题讨论】:

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


    【解决方案1】:

    最简单的例子是这样的

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

    【讨论】:

    • 感谢您的回答,但我之前已经找到了这个解决方案。这对我来说并不令人满意。我真的需要同步进行。
    • 请问为什么?我很好奇。
    • 此应用程序将使用许多不同的文化。每个新线程都以默认文化启动,这对我来说不是预期的行为。我也不能使用 CultureInfo.DefaultThreadCurrentCulture,因为 .NET 4.0 尚不支持它。
    • 我明白了。您是否考虑过这种解决方法? stackoverflow.com/questions/20601578/…
    • 这对我来说看起来不错,但我仍然很好奇是否可以同步进行
    【解决方案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");        
        }
    

    【讨论】:

    • 那是 MVC,没有 WebAPI :)
    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 2015-02-18
    相关资源
    最近更新 更多