有没有办法同步处理发布到ASP.Net Web API中控制器的上传文件?
我已经尝试了微软提出的here过程,它按照描述的方式工作,但我想返回一个不同于Task<>的东西。从Controller方法开始,以匹配我的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
}
同样,我已经使异步示例工作,但我希望能够在响应客户端之前处理上传的文件。
答案 0 :(得分: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。