2016-04-22 9 views
3

Ich lade ein Bild mit Web-API.zurück Dateiname nach dem Speichern in 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" })); 
    } 
} 

Above Code habe ich verwendet Bild zu speichern, aber jedes Mal filedescription auch nach Bild erfolgreich gespeichert wird. Was ist los, mache ich hier.

Ich möchte Dateibeschreibung nach Bild speichern zurückgeben.

Antwort

0

Sie verwenden eine Menge von async Methoden in der falschen Weise. Sie sollten niemals eine async-Methode anrufen und dann darauf warten, dass sie synchron beendet wird (z. B. mit Wait() oder Result).

Wenn eine API eine async Methode verfügbar macht, dann await dafür, indem sie auch die aufrufende Methode in eine async Methode umwandelt.

Der Grund, warum Ihre filedescription Variable immer Null ist, liegt daran, dass Sie es überprüfen, bevor Sie die Fortsetzung beendet haben. Das ist wirklich eine schlechte Übung: Wenn Sie einen Wert benötigen, der ein Ergebnis einer Operation async ist, müssen Sie warten, bis es fertig ist, aber in diesem Fall mit dem Schlüsselwort await.

Dies ist der richtige Weg, async Methoden aufrufen und (asynchron) warten, bis sie fertig:

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" })); 
    } 
} 
Verwandte Themen