我目前正在使用.NET SDK从Amazon S3下载文件,我目前有以下代码(仅允许这些文件):
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 :(得分:3)
好的,对于#1,不要在MemoryStream上使用GetBuffer
。使用ToArray
:
Dim bytes = strReader.ToArray()
Response.OutputStream.Write(bytes, 0, bytes.Length)
GetBuffer
返回缓冲区,而不是写入流的内容。
对于#2,您需要为.***x
Office文档使用不同的MIME类型。请参阅here。
答案 1 :(得分:1)
以下代码将从该位置获取文件并将其自动下载到浏览器中,而不会收到损坏的文件警告。
using(var response = client.GetObjectAsync(request).Result)
{
using( var responseStream = response.ResponseStream )
{
Response.ContentType = response.Headers.ContentType;
Response.AddHeader("Content-Length", response.Headers.ContentLength.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + uri.Key + "\"");
Response.ContentType = "application/octet-stream";
var memoryStream = new MemoryStream();
responseStream.CopyTo(memoryStream);
Response.BinaryWrite(memoryStream.ToArray()); //All byte data is converting to files
}
}
答案 2 :(得分:-1)
感谢您的努力,但我们可以通过以二进制格式发送正文中的文件来解决此问题。
const uploadS3 = (url,file) =>{
var requestOptions = {
method: 'PUT',
body: file,
redirect: 'follow',
};