c# - 下载 Amazon S3 对象,Windows 说文件已损坏

标签 c# .net vb.net amazon-s3 amazon-web-services

我目前正在使用 .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

我有 2 个问题:首先,当我尝试在客户端窗口上打开文件时,告诉我(对于 MS office 文件)文件已损坏,有时它设法打开它们,有时则不能。其次,似乎如果我的文件具有 .pptx 之类的扩展名,并且我在内容类型中说“PowerPoint”,浏览器似乎会尝试向它们附加一个扩展名,例如“.ppt”或“.doc”。有什么办法可以解决这个问题吗?

编辑:打开 MS Office 文件时收到的实际消息:“PowerPoint 在 PowerPointFile.ppt 中发现不可读的内容。您要恢复此演示文稿的内容吗?如果您信任此演示文稿的来源,请单击"is"。

最佳答案

好的,对于 #1,不要在 MemoryStream 上使用 GetBuffer。使用 ToArray :

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

GetBuffer 返回缓冲区,而不是写入流的内容。

对于 #2,您需要为 .***x Office 文档使用不同的 MIME 类型。参见 here .

关于c# - 下载 Amazon S3 对象,Windows 说文件已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13635210/

相关文章:

c# - ASP.NET Identity - 无法注册 UserTokenProvider

c# - 当原始请求有内容时如何克隆 HttpRequestMessage?

c# - 如何将字节数组转换回文件并使用 C# 自动打开它?

.net - 创建 .NET 组件,例如 Windows 搜索工具栏

vb.net - 不要使用数组列表!

c# - 使用 NUnit 断言集合中的所有项目都具有其中一个项目属性的值

c# - 使用导航服务在页面之间进行动画转换

.net - MEF 导入在 Windows 服务中失败

vb.net - 如何使用 vb.net 获取子字符串日期(年份)?

vb.net - 检查 textbox.text 是否存在于数组中