2016-04-22 53 views
3

我使用Web API上傳圖像。保存在WebAPi中後返回文件名

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。我在這裏做什麼錯。

我想在保存圖像後返回filedescription。

回答

0

您以錯誤的方式使用了很多async方法。您不應該撥打async方法,然後等待它以同步方式完成(例如,使用Wait()Result)。

如果一個API公開一個async方法,然後await它,也將調用方法轉變爲一個async方法。

您的filedescription變量始終爲空的原因是因爲您在繼續完成之前檢查它。這確實是一個不好的做法:如果您需要的值是async操作的結果,那麼您必須等待它完成,但在這種情況下,請使用await關鍵字。

這是調用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" })); 
    } 
}