2013-05-07 84 views
7

我正嘗試通過multipart/form-data文章上傳圖像,並使用下面的代碼。我只會上傳.jpg圖片。通過表單上傳圖像文件

問題是保存的圖像不是有效圖像,無法查看。它比我上傳的文件大200字節,所以我假設我在這裏錯過了一些東西?

public class FileUploadController : ApiController 
{ 
    public Task<HttpResponseMessage> PostUploadFile() 
    { 
     return UploadFileAsync().ContinueWith<HttpResponseMessage>((tsk) => 
      { 
       HttpResponseMessage response = null; 

       if (tsk.IsCompleted) 
       { 
        response = new HttpResponseMessage(HttpStatusCode.Created); 
       } 
       else if (tsk.IsFaulted || tsk.IsCanceled) 
       { 
        response = 
        new HttpResponseMessage(HttpStatusCode.InternalServerError); 
       } 

       return response; 
      }); 
    } 

    public Task UploadFileAsync() 
    { 
     return this.Request.Content.ReadAsStreamAsync().ContinueWith((tsk) => 
     { SaveToFile(tsk.Result); }, 
     TaskContinuationOptions.OnlyOnRanToCompletion); 
    } 

    private void SaveToFile(Stream requestStream) 
    { 
     string path = 
     System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory); 
     using (FileStream targetStream = 
     File.Create(path + "/Uploads/" + DateTime.Now.ToFileTime() + ".jpg")) 
     { 
      using (requestStream) 
      { 
       requestStream.CopyTo(targetStream); 
      } 
     } 
    } 
} 

下面是我用來發布圖片的簡單表單。

<form action="/api/postuploadfile" enctype="multipart/form-data" method="post"> 
    Upload Image: 
    <input type="file" id="imagename" name="imagename" /> 
    <input type="submit" /> 
</form> 

信息有關圖像,前/後:
如果我檢查我上傳的圖片的屬性,則磁盤大小是一樣的原始圖像,但大小屬性是200-205個字節大。無論我上傳的圖片有多大,情況總是如此。

這是POST標題的一部分。我不需要去除邊界部分或其他東西?

Source 
-----------------------------1944294225892 Content-Disposition: form-data; 
name="imagename"; filename="small.jpg" Content-Type: image/jpeg 

而且一些報頭......

Request Headers From Upload Stream 
Content-Length 125661 
Content-Type multipart/form-data; boundary=---------------------------1944294225892 
+0

對我來說沒關係,編碼問題也許呢? – 2013-05-07 08:02:32

回答