Downloading Amazon S3 objects, Windows says files are corrupted
I am currently downloading Files from Amazon S3 using the .NET SDK, I currently have the following code to do it (only these files are allowed):
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
I am having 2 problems: first, when I try to open the files on the client windows tells me (for MS office files) that the files are corrupted, somtimes it manages to open them anyway, sometimes not. Second, it seems that if I the files have extensions like .pptx, and I say 'PowerPoint' in the content type, it seems like the browser tries to append an extension to them like '.ppt' or '.doc'. Any way to fix that?
EDIT: actual message that I am getting when opening a MS office file: 'PowerPoint found unreadable content in PowerPointFile.ppt. Do you want to recover the contents of this presentation? If you trust the source of this presentation, click Yes.
OK, for #1, don't use GetBuffer
on MemoryStream. Use ToArray
:
Dim bytes = strReader.ToArray()
Response.OutputStream.Write(bytes, 0, bytes.Length)
GetBuffer
returns the buffer, not what was written to the stream.
For #2, you need to use a different MIME type for .***x
Office documents. See here.
上一篇: 是否有可能强制Excel识别UTF