我正在使用Web API上传图片。
public IHttpActionResult UploadImage()
{
FileDescription filedescription = null;
var allowedExt=new string[]{".png",".jpg",".jpeg"};
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (Request.Content.IsMimeMultipartContent())
{
Request.Content.LoadIntoBufferAsync().Wait();
var imgTask = Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(new MultipartMemoryStreamProvider()).ContinueWith((task) =>
{
MultipartMemoryStreamProvider provider = task.Result;
var content = provider.Contents.ElementAt(0);
Stream stream = content.ReadAsStreamAsync().Result;
Image image = Image.FromStream(stream);
var receivedFileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
var getExtension = Path.GetExtension(receivedFileName);
if(allowedExt.Contains(getExtension.ToLower())){
string newFileName = "TheButler" + DateTime.Now.Ticks.ToString() + getExtension;
var originalPath = Path.Combine("Folder Path Here", newFileName);
image.Save(originalPath);
var picture = new Images
{
ImagePath = newFileName
};
repos.ImagesRepo.Insert(picture);
repos.SaveChanges();
filedescription = new FileDescription(imagePath + newFileName, picture.Identifier);
}
});
if (filedescription == null)
{
return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, new { message="some error msg."}));
}
else
{
return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, filedescription));
}
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, new { message = "This request is not properly formatted" }));
}
}
上面的代码我已经习惯了保存图片,但每次filedescription
甚至在图像成功保存之后。我在这里做错了什么。
我想在图像保存后返回文件描述。
答案 0 :(得分:0)
您以错误的方式使用了大量async
方法。您永远不应该调用async
方法,然后等待它以同步方式完成(例如,使用Wait()
或Result
)。
如果API公开async
方法,然后await
,则将调用方法转换为async
方法。
您的filedescription
变量始终为空的原因是因为您在继续完成之前检查它。这确实是一种不好的做法:如果您需要的值是async
操作的结果,那么您必须等待它完成,但在这种情况下,请使用await
关键字。< / p>
这是调用async
方法并等待(异步)完成它们的正确方法:
public async Task<IHttpActionResult> UploadImage()
{
FileDescription filedescription = null;
var allowedExt = new string[] { ".png", ".jpg", ".jpeg" };
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (Request.Content.IsMimeMultipartContent())
{
await Request.Content.LoadIntoBufferAsync();
var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
var content = provider.Contents.ElementAt(0);
Stream stream = await content.ReadAsStreamAsync();
Image image = Image.FromStream(stream);
var receivedFileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
var getExtension = Path.GetExtension(receivedFileName);
if (allowedExt.Contains(getExtension.ToLower()))
{
string newFileName = "TheButler" + DateTime.Now.Ticks.ToString() + getExtension;
var originalPath = Path.Combine("Folder Path Here", newFileName);
image.Save(originalPath);
var picture = new Images
{
ImagePath = newFileName
};
repos.ImagesRepo.Insert(picture);
repos.SaveChanges();
filedescription = new FileDescription(imagePath + newFileName, picture.Identifier);
}
if (filedescription == null)
{
return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, new { message = "some error msg." }));
}
else
{
return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, filedescription));
}
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, new { message = "This request is not properly formatted" }));
}
}