问题
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