【发布时间】:2017-04-27 11:55:32
【问题描述】:
有问题的 PowerPoint 文件大小为 18mb。单击按钮后,将调用控制器中的以下 GET 方法:
[Route("api/download/GetFile")]
[HttpGet]
public HttpResponseMessage GetFile()
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
try
{
var localFilePath = HttpRuntime.AppDomainAppPath + "content\\files\\file.pptx";
var stream = File.OpenRead(localFilePath);
stream.Position = 0;
stream.Flush();
if (!System.IO.File.Exists(localFilePath))
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
byte[] buffer = new byte[(int)stream.Length];
result.Content = new ByteArrayContent(buffer);
result.Content.Headers.Add("Content-Type", "application/pptx");
result.Content.Headers.Add("x-filename", "file.pptx");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.Add("Content-Length", stream.Length.ToString());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.presentationml.presentation");
}
return result;
}
catch (Exception e)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
文件通过浏览器下载到下载文件夹,大小与服务器上调用下载的原始文件完全相同。但是,当尝试打开它时:
"PowerPoint 在 file.pptx 中发现不可读的内容。您要 恢复此演示文稿的内容?如果你相信来源 此演示文稿,请单击是。”
单击“是”只会使 PowerPoint 加载一段时间,然后返回错误消息“访问此文件时出现问题”。
我怀疑问题出在这个“x-filename”上,但是将这个值更改为其他值最终会使浏览器下载一个只有几 KB 的 bin 文件。我还尝试将 ContentType 和 MediaTypeHeaderValue 更改为许多不同的东西(应用程序/pptx、应用程序/x-mspowerpoint 等),但没有任何效果。此外,我还尝试像这样分配内容:
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
这也不起作用。
任何帮助表示赞赏。
编辑:
正如 Hans Kesting 指出的那样,我似乎没有正确复制字节。但是,尝试打开 powerpoint 文件时,执行以下操作仍然会产生相同的错误消息,但文件现在大小为 33mb:
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
byte[] buffer = memoryStream.ToArray(); // stream.CopyTo// new byte[(int)stream.Length];
result.Content = new ByteArrayContent(buffer);
当我以错误的方式复制字节时,为什么下载的文件与原始文件的字节数完全相同,但现在却有 33 mb?
【问题讨论】:
-
帮不了你,但你先打开文件,然后检查它是否存在?
-
对于 mimetypes,请参阅 filext.com/faq/office_mime_types.php
-
建议:Windows 操作系统中的最大路径长度为 255 个字符。看看你有没有 - 我有这个问题,文件所在的路径超过 255 个字符。它下载了文件,在那里,但无法打开。
-
@HansKesting 是的,在发布这个问题之前,我已经从该链接尝试了所有与 powerpoint 相关的 mimetypes :) 并且文件存在后的检查......这只是一些剩余的时间我试图重写此方法以正确下载文件... :(
-
@CalinVlasin 感谢您的评论:我刚刚检查了它,路径是 99 个字符,所以应该不错。
标签: asp.net powerpoint