ASP.NET 下载的文件已损坏
我编写了以下代码来从共享点下载文件。下载的文件仅在某些机器上运行良好。对于其他人,它表示文件已损坏。该问题针对 MS Office 和图像文件,但 PDF 没有任何问题。我们已确定损坏问题是由于在文件内容顶部添加了十六进制数字所致。删除后,文件将被正确打开。已查出十六进制字符表示文件大小(以字节为单位)。为什么这种情况只发生在某些机器上,我们如何解决它?
private void DownloadFile()
{
SPListItem item = GetFileFromSharepoint();
if (item != null)
{
byte[] bytes = item.File.OpenBinary();
Response.ClearContent();
Response.ClearHeaders();
string fileType = string.Empty;
fileType = item["FileFormat"].ToString();
Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename= {0}", item["Filename"].ToString().Replace(" ", "")));
Response.ContentType = GetContentType(fileType);
//Check that the client is connected and has not closed the connection after the request
if (Response.IsClientConnected)
{
Response.BinaryWrite(bytes);
}
}
Response.Flush();
Response.Close();
}
I have written the following code to download a file from sharepoint. The downloded file works fine in only some machines. For others, it says that the file is corrupted. The issue is for MS Office and image files, however the PDF is not having any issues. We have identified the issue of corruption as due to the addition of a hexadecimal number at the top of the file contents. When it is removed, the file gets opened correctly. The hexadecimal character has been traced out to be representing the file size in bytes. Why this is happening only in some machines and how can we fix it?
private void DownloadFile()
{
SPListItem item = GetFileFromSharepoint();
if (item != null)
{
byte[] bytes = item.File.OpenBinary();
Response.ClearContent();
Response.ClearHeaders();
string fileType = string.Empty;
fileType = item["FileFormat"].ToString();
Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename= {0}", item["Filename"].ToString().Replace(" ", "")));
Response.ContentType = GetContentType(fileType);
//Check that the client is connected and has not closed the connection after the request
if (Response.IsClientConnected)
{
Response.BinaryWrite(bytes);
}
}
Response.Flush();
Response.Close();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从文档来看,似乎表明:
您确定该函数的返回值是正确的吗?您没有检查
bytes
数组的长度。更新:
也许将
SPOpenBinaryOptions.Unprotected
传递给OpenBinary
可能有效吗?From the documentation, it would appear to suggest that:
Are you certain that the return value from this function is correct? You are not checking the length of the
bytes
array.Update:
Perhaps passing
SPOpenBinaryOptions.Unprotected
toOpenBinary
might work?