3

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

我已经尝试过 Microsoft在此处提出的流程,它的工作原理与描述的一样,但我想从 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
}

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

4

1 回答 1

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. 这是Web API 团队经过深思熟虑的选择,您可以根据需要进行覆盖。

于 2012-08-28T18:26:57.443 回答