【问题标题】:ASP.Net Web API - Get POSTed file synchronously?ASP.Net Web API - 同步获取 POSTed 文件?
【发布时间】:2012-08-28 17:01:15
【问题描述】:

有没有办法在 ASP.Net Web API 中同步处理上传到控制器的上传文件?

我已经尝试过 Microsoft 提出的 here 流程,它的工作原理与描述的一样,但我想从 Controller 方法返回 Task 以外的其他内容,以匹配我的 RESTful API 的其余部分。

基本上,我想知道是否有任何方法可以使这项工作:

public MyMugshotClass PostNewMugshot(MugshotData data){
    //get the POSTed file from the mime/multipart stream <--can't figure this out
    //save the file somewhere
    //Update database with other data that was POSTed
    //return a response
}

再次,我已经使异步示例工作,但我希望有一种方法可以在响应客户端之前处理上传的文件。

【问题讨论】:

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


【解决方案1】:
public class UploadController : ApiController
{
    public async Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var appData = HostingEnvironment.MapPath("~/App_Data");
        var folder = Path.Combine(appData, Guid.NewGuid().ToString());
        Directory.CreateDirectory(folder);
        var provider = new MultipartFormDataStreamProvider(folder);
        var result = await Request.Content.ReadAsMultipartAsync(provider);
        if (result.FileData.Count < 1)
        {
            // no files were uploaded at all
            // TODO: here you could return an error message to the client if you want
        }

        // at this stage all files that were uploaded by the user will be
        // stored inside the folder we specified without us needing to do
        // any additional steps

        // we can now read some additional FormData
        string caption = result.FormData["caption"];

        // TODO: update your database with the other data that was posted

        return Request.CreateResponse(HttpStatusCode.OK, "thanks for uploading");
    }
}

您可能会注意到上传的文件存储在指定的文件夹中,其名称可能如下所示:BodyPart_beddf4a5-04c9-4376-974e-4e32952426ab。这是一个 deliberate choice that the Web API team made,您可以根据需要覆盖它。

【讨论】:

  • 如何以适当的扩展名保存文件,以便正确读取它们?当文件没有扩展名时,你怎么知道如何打开它。这似乎是糟糕的设计。
  • @jaffa,通常我将文件的 mime 类型和物理位置存储在后端。那么磁盘上文件的物理名称并不重要。我已经在需要时掌握了这些信息。
  • 这不是问题的答案。这会异步处理请求。最初的问题是同步处理。
  • 发帖者要求同步处理文件上传,此代码使用异步。
  • 这是怎么同步的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
  • 2019-08-06
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
相关资源
最近更新 更多