PDF file download from byte[]

邮差的信 提交于 2019-12-12 01:16:20

问题


I've been working to do a PDF file download from bytes[] in ASP.Net MVC C#. The below code is working fine.

I need to convert the code to .NET Core for the same PDF download process.

string fileName = "testFile.pdf";

byte[] pdfasBytes = Encoding.ASCII.GetBytes(fileBytes);   // Here the fileBytes are already encoded (Encrypt) value. Just convert from string to byte
Response.Clear();
MemoryStream ms = new MemoryStream(pdfasBytes);
Response.ContentType = "application/pdf";
Response.Headers.Add("content-disposition", "attachment;filename=" + fileName);
Response.Buffer = true;
ms.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();

I'm tried to convert the above code to .NET Core. I get an error: OutputStream method doesn't contain Response for this ms.WriteTo(Response.OutputStream) line. Thanks In advance.!


回答1:


@Luaan sir already gave answer, but it may be my code also help you, so I share it.

Download Pdf file from folder

[HttpGet]
        public FileStreamResult DownloadPdfFile(string fileName)
        {            
            var stream = new FileStream(Directory.GetCurrentDirectory() + "\\wwwroot\\WriteReadData\\" + fileName, FileMode.Open);
            return new FileStreamResult(stream, "application/pdf");
        }

Download pdf file from database

[HttpGet]
        public FileStreamResult DownloadFileFromDataBase(string id)
        {
            var _fileUpload = _db.FileUpload.SingleOrDefault(aa => aa.fileid == id);         // _fileUpload.FileContent type is byte
            MemoryStream ms = new MemoryStream(_fileUpload.FileContent);
            return new FileStreamResult(ms, "application/pdf");
        }

For more info please also see this question and answer. Return PDF to the Browser using Asp.net core




回答2:


MVC has simplified this. All you need is to have an action that returns ActionResult:

public ActionResult GetImage()
{
  string fileName = "testFile.pdf";
  var pdfasBytes = ...;

  return File(pdfasBytes, "application/pdf", fileName);
}


来源:https://stackoverflow.com/questions/57353719/pdf-file-download-from-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!