从服务器下载.pptx文件到客户端 - ASP.NET
有问题的PowerPoint文件大小为18mb。点击一个按钮后,在一个控制器下面的GET方法被称为:从服务器下载.pptx文件到客户端 - ASP.NET
[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文件名”内,但将此值更改为其他内容最终导致浏览器仅用几KB下载bin文件。我也尝试将ContentType和MediaTypeHeaderValue更改为许多不同的东西(application/pptx,application/x-mspowerpoint等),但是没有什么关键技巧。此外,我也尝试这样分配内容:
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
这也不起作用。
任何帮助表示赞赏。
编辑:
正如汉斯合成聚合物膜指出,看来我是没有正确复制字节。然而,在做下面当试图打开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?
byte[] buffer = new byte[(int)stream.Length];
result.Content = new ByteArrayContent(buffer);
这意味着您有一个正确大小的缓冲区,但为空。您仍然需要从该流中填充它。
感谢您的回答!我试图填充缓冲区(希望现在有一个好的方法),但问题仍然存在。看我的编辑。 –
它不会帮你,但首先你打开文件,然后*检查它是否存在? –
for mimetypes,请参阅http://filext.com/faq/office_mime_types.php –
建议:Windows操作系统中的最大路径长度为255个字符。看看你是否有 - 我有这个问题,文件的路径是超过255个字符。它下载了文件,在那里,但无法打开。 –