C#WebAPI使用内存流下载PowerPoint文件

到目前为止,这是我下载powerpoint文件的代码。我为powerpoint使用了aspose软件包,这是指向aspose文档https://docs.aspose.com/dashboard.action

的链接
    [HttpGet]
    [Route("exportpowerpoint1")]
    public HttpResponseMessage Export()
    {           
        using (Presentation presentation = new Presentation(HttpContext.Current.Server.MapPath("~/PPTexports/testfile.pptx")))
        {
            MemoryStream stream = new MemoryStream();
            presentation.Save(stream,SaveFormat.Pptx);
            stream.Position = 0;
            var returnResult = Request.CreateResponse(HttpStatusCode.OK);
            returnResult.Content = new StreamContent(stream);
            returnResult.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.presentationml.presentation");
            returnResult.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "testfile.pptx"
            };                
            return returnResult;
        }}

使用此代码,我可以下载文件,但是当我打开文件时,powerpoint会显示此错误消息,并且文件大小也加倍

Error message: powerpoint found unreadable content in testfile.pptx

我认为内存流两次写入文件,这是大小增加一倍并且由于重复的内容而导致文件无法打开的原因,但是我无法找到问题的原因有人可以帮忙吗?

la_zhanghui 回答:C#WebAPI使用内存流下载PowerPoint文件

尝试一下:

[HttpGet]
[Route("exportpowerpoint1")]
public HttpResponseMessage Export()
{   
    var returnResult = Request.CreateResponse(HttpStatusCode.OK);
    returnResult.Content = new StreamContent(File.OpenRead(HttpContext.Current.Server.MapPath("~/PPTexports/testfile.pptx")));
    returnResult.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.presentationml.presentation");
    returnResult.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "testfile.pptx"
    };                
    return returnResult;
}
,

不要做我所做的事情,并将MemoryStream放在using块中……您将不会得到任何响应,因为它在内容发送之前就已经被丢弃了。

本文链接:https://www.f2er.com/3067997.html

大家都在问