2013-05-28 75 views
8

我目前能夠保存上傳到WebAPI控制器的文件,但我希望能夠將該文件保存爲帶有正確文件擴展名的guid所以它可以被正確地查看。使用guid和文件擴展名ASP.NET WebApi文件上傳

代碼:

[ValidationFilter] 
    public HttpResponseMessage UploadFile([FromUri]string AdditionalInformation) 
    { 
     var task = this.Request.Content.ReadAsStreamAsync(); 
     task.Wait(); 

     using (var requestStream = task.Result) 
     { 
      try 
      { 
       // how can I get the file extension of the content and append this to the file path below? 

       using (var fileStream = File.Create(HttpContext.Current.Server.MapPath("~/" + Guid.NewGuid().ToString()))) 
       { 
        requestStream.CopyTo(fileStream); 
       } 
      } 
      catch (IOException) 
      {      
       throw new HttpResponseException(HttpStatusCode.InternalServerError); 
      } 
     } 

     HttpResponseMessage response = new HttpResponseMessage(); 
     response.StatusCode = HttpStatusCode.Created; 
     return response; 
    } 

我似乎無法得到關於內容的實際文件名的手柄。我認爲headers.ContentDisposition.FileName可能是一個候選人,但似乎並沒有填充。

+0

這裏是使用應答類似的問題[http://stackoverflow.com/questions/14937926/file-name-from-httprequestmessage-content][1] [1]: http://stackoverflow.com/questions/14937926/file-name-from-httprequestmessage-content – forseta

+0

你能分享你的請求標題的樣子嗎?您是否在請求中填充了ContentDisposition標頭? –

+0

客戶端負責設置此類標頭。你的客戶是什麼樣的? – Snixtor

回答

18

感謝上面的評論,這些評論指出了我的正確方向。

爲了澄清最終的解決方案,我使用了一個MultipartFormDataStreamProvider,它自動將文件流式傳輸。代碼是在另一個問題,我發佈到不同的問題在這裏: MultipartFormDataStreamProvider and preserving current HttpContext

我的完整供應商代碼被列在下面。生成guid文件名的關鍵是重寫GetLocalFileName函數並使用headers.ContentDisposition屬性。提供者處理將內容流式傳輸到文件。

public class MyFormDataStreamProvider : MultipartFormDataStreamProvider 
{ 
    public MyFormDataStreamProvider (string path) 
     : base(path) 
    { } 

    public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) 
    { 
     // restrict what images can be selected 
     var extensions = new[] { "png", "gif", "jpg" }; 
     var filename = headers.ContentDisposition.FileName.Replace("\"", string.Empty); 

     if (filename.IndexOf('.') < 0) 
      return Stream.Null; 

     var extension = filename.Split('.').Last(); 

     return extensions.Any(i => i.Equals(extension, StringComparison.InvariantCultureIgnoreCase)) 
        ? base.GetStream(parent, headers) 
        : Stream.Null; 

    } 

    public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) 
    { 
     // override the filename which is stored by the provider (by default is bodypart_x) 
     string oldfileName = headers.ContentDisposition.FileName.Replace("\"", string.Empty); 
     string newFileName = Guid.NewGuid().ToString() + Path.GetExtension(oldfileName); 

     return newFileName;  
    } 
} 
+1

在'var filename = headers.ContentDisposition.FileName.Replace(「\」「,string.Empty);'處引發一個空引用異常。'通過在執行'Replace()'之前檢查'filename'是否爲空來修復。 –

+0

你爲什麼重寫GetStream方法? –