本文介绍了如何发布文件到ASP.NET网页API 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个文件发布到我的WebAPI。这不是问题,但:

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


  1. 我不想使用JavaScript

  2. 文件必须接收并保存的同步

  3. 我想我的行动看起来像这样:

  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)
{

}

public void Post(Stream stream)
{

}


  • 我要发布从code similiar文件本(当然,现在它不工作):

  • 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>
    


  • 任何建议将AP preciated

    Any suggestions will be appreciated

    推荐答案

    最简单的例子是这样的。

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

    ReadAsMultipartAsync 不同步的版本,所以你最好一起演奏。

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

    更新:

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

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

    这篇关于如何发布文件到ASP.NET网页API 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-29 01:30