简体   繁体   中英

C# WebAPI to download PowerPoint file using memory stream

This is my code so far to download the powerpoint file. I used aspose package for powerpoint this is the link to the aspose documentation 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;
        }}

with this code, I'm able to download the file but when I open the file then powerpoint gives this error message and the size of the file is also got double

Error message: powerpoint found unreadable content in testfile.pptx

I think the memory stream writes the file two times that is the reason size got double and file can't open because of duplicate content but I'm unable to find the cause of the issue can anybody help?

Try this:

[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;
}

Don't do what I did and put the MemoryStream in a using block... you will get no response since it has been disposed before the content has been sent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM