gpt4 book ai didi

c# - 如何使用 asp.net 和 c# 流式传输 Excel 2007 或 Word 2007 文件

转载 作者:可可西里 更新时间:2023-11-01 08:06:04 25 4
gpt4 key购买 nike

我正在开发一个网络应用程序,需要流式传输各种文件。我可以处理 pdf、图像和旧版 Office 文档。但是,当我尝试处理 2007 文档时,它会中断。这是我的代码:

    Response.Buffer = true;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
switch (FileExtension.ToLower())
{
case "pdf":
Response.ContentType = "application/pdf";
break;
case "doc":
Response.ContentType = "application/msword";
break;
case "docx":
Response.ContentType = "application/vnd.ms-word.document.12";
break;
case "xls":
Response.ContentType = "application/vnd.ms-excel";
break;
case "xlsx":
Response.ContentType = "application/vnd.ms-excel.12";
break;
default:
Response.ContentType = "image/jpeg";
break;
}
Response.BinaryWrite(buffer);

我得到的错误是:

An invalid character was found in text content. Error processing resource 'http://DomainName/GetFile.aspx...PK

有什么建议吗?

最佳答案

根据简单的网络搜索,word和excel的正确mime类型是:

application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

http://www.bram.us/2007/05/25/office-2007-mime-types-for-iis/

编辑:

以下简化示例适合我。它与您的不同之处在于它使用通用处理程序而不是 Web 表单(无论如何更适合这样的事情)。

要对其进行测试,请确保在应用程序的顶级文件夹中有一个名为 Book1.xlsx 的 excel 2007 文件。

DownloadSpreadsheet.ashx:

<%@ WebHandler Language="C#" Class="DownloadSpreadsheetHandler" %>

using System;
using System.Web;
using System.IO;

public class DownloadSpreadsheetHandler: IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
string path = context.Server.MapPath("~/Book1.xlsx");
using (FileStream spreadsheet = File.OpenRead(path))
{
CopyStream(spreadsheet, context.Response.OutputStream);
}
}

public bool IsReusable {
get {
return false;
}
}

private static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
while (true)
{
int read = input.Read(buffer, 0, buffer.Length);
if (read <= 0)
return;
output.Write(buffer, 0, read);
}
}

}

关于c# - 如何使用 asp.net 和 c# 流式传输 Excel 2007 或 Word 2007 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2519026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com