2014-03-13 77 views
2

我想從(DHC by Restlet)上傳圖像到我的C#API。將來我想從Android或iPhone應用程序中調用此API,但我發現在任何此類設備上實現它之前,我需要這部分工作。從HTTP客戶端上傳到C#Web Api的圖像

這個C#代碼放在我的api:s ValuesController中。我默認呼叫的控制器。我已經確定(通過斷點)下面的方法是可訪問和正確調用的。

public async Task<HttpResponseMessage> PostFormData() 
    { 
     // Check if the request contains multipart/form-data. 
     if (!Request.Content.IsMimeMultipartContent()) 
     { 
      throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
     } 

     string root = HttpContext.Current.Server.MapPath("~/App_Data"); 
     var provider = new MultipartFormDataStreamProvider(root); 

     try 
     { 
      // Read the form data. 
      await Request.Content.ReadAsMultipartAsync(provider); 

      // This illustrates how to get the file names. 
      foreach (MultipartFileData file in provider.FileData) 
      { 
       Trace.WriteLine(file.Headers.ContentDisposition.FileName); 
       Trace.WriteLine("Server file path: " + file.LocalFileName); 
      } 
      return Request.CreateResponse(HttpStatusCode.OK); 
     } 
     catch (System.Exception e) 
     { 
      return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); 
     } 
    } 

。但是,我在嘗試發佈png格式我的服務時,出現以下錯誤:

System.IO.IOException was caught 
    HResult=-2146232800 
    Message=Unexpected end of MIME multipart stream. MIME multipart message is not complete. 
    Source=System.Net.Http.Formatting 
    StackTrace: 
    at System.Net.Http.Formatting.Parsers.MimeMultipartBodyPartParser.<ParseBuffer>d__0.MoveNext() 
    at System.Net.Http.HttpContentMultipartExtensions.MoveNextPart(MultipartAsyncContext context) 
--- End of stack trace from previous location where exception was thrown --- 
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() 
    at Nutris.Webapi.Controllers.ValuesController.<PostFormData>d__12.MoveNext() in c:\Users\Simon\Documents\GitHub\Nutris\Nutris.Webapi\Controllers\ValuesController.cs:line 836 

的InnerException:

它發生在該行:

await Request.Content.ReadAsMultipartAsync(provider); 

我錯過了什麼?感覺就像我忘了提及上述方法的mimetype。

回答

0

檢查發送數據的輸入。

確保它有自己的基本屬性設置,如:

  • 名稱:
  • 類型:
  • 值:(我不認爲這是有必要)

    <input type="file" name="dataFile" value="Choose..." multiple/> 
    

這些都是MIME被認爲是完整的,可以映射的所有必要corr通過你的處理程序。

你應該發佈你的HTML代碼,以確保它是同一個問題。