2012-11-29 59 views
2

目前我正在從Amazon S3使用.NET SDK下載文件,我現在有下面的代碼來做到這一點(只有這些文件被允許):下載Amazon S3的對象,說的Windows文件被損壞

With request 
     .WithBucketName(bucketName) 
     .WithKey(key) 
    End With 
    response2 = client.GetObject(request) 
    Dim strReader As MemoryStream = New MemoryStream 
    response2.ResponseStream.CopyTo(strReader) 

    Response.ContentType = getContentType(key) 
    Response.OutputStream.Write(strReader.GetBuffer, 0, strReader.GetBuffer.Length) 
    Dim fileName As String = Path.GetFileName(key) 
    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName) 
    Return "" 

End Function 
Private Function getContentType(ByVal fileToContent As String) As String 
    Dim fileExtension As String = Path.GetExtension(fileToContent) 
    Dim contentType As String 
    Select Case fileExtension 
     Case ".bmp" 
      contentType = "image/bmp" 
     Case ".png" 
      contentType = "image/png" 
     Case ".xlsx", ".xls" 
      contentType = "application/vnd.ms=excel" 
     Case ".jpg", ".jpeg", ".gif" 
      contentType = "image/jpeg" 
     Case ".pdf" 
      contentType = "application/pdf" 
     Case ".ppt", ".pptx" 
      contentType = "application/vnd.ms-powerpoint" 
     Case ".doc", ".docx" 
      contentType = "application/msword" 
     Case Else 
      contentType = "text/plain" 
    End Select 
    Return contentType 
End Function 

我有兩個問題:第一,當我嘗試打開客戶端窗口上的文件時告訴我(MS Office文件)文件已損壞,有時無論如何設法打開它們,有時不是。其次,如果我的文件有類似.pptx的擴展名,並且我在內容類型中說'PowerPoint',那麼瀏覽器似乎會試圖向它們添加一個擴展名,如'.ppt'或'.doc'。有什麼辦法解決這個問題?

編輯:打開MS Office文件時我得到實際的消息:「PowerPoint發現在PowerPointFile.ppt不可讀的內容。你想恢復本演示文稿的內容嗎?如果您信任此演示文稿的來源,請單擊是。

+0

關於#2,您需要爲'。*** x' Office文檔使用不同的MIME類型。請參閱[這裏](http://stackoverflow.com/a/4212908/492405) – vcsjones

+0

好吧,我現在沒有打開文件的問題,雖然我仍然從窗口中打開它們之前得到那個神祕的錯誤信息。 –

回答

3

OK,#1,不要MemoryStream的使用GetBuffer。使用ToArray

Dim bytes = strReader.ToArray() 
Response.OutputStream.Write(bytes, 0, bytes.Length) 

GetBuffer返回緩衝區,而不是什麼寫入流。

#2,您需要使用不同的MIME類型.***x Office文檔。請參閱here