[英]ASP.Net Web API - Get POSTed file synchronously?
有没有办法同步处理发布到ASP.Net Web API中的控制器的上传文件?
我已经尝试了微软在这里提出的过程,它按照描述工作,但是我想从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
}
我再次使异步示例工作,但我希望在响应客户端之前处理上传文件的方法。
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团队的一个深思熟虑的选择,您可以根据需要进行覆盖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.