【问题标题】:PDF file download from byte[]从 byte[] 下载 PDF 文件
【发布时间】:2019-08-05 07:09:13
【问题描述】:

我一直致力于在 ASP.Net MVC C# 中从bytes[] 下载PDF 文件。下面的代码工作正常。

我需要将代码转换为.NET Core 以实现相同的PDF 下载过程。

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();

我试图将上面的代码转换为.NET Core。我收到一个错误:OutputStream 方法不包含此 ms.WriteTo(Response.OutputStream) 行的响应。 提前致谢!

【问题讨论】:

  • 我很确定 byte[] pdfasBytes = Encoding.ASCII.GetBytes(fileBytes) 没有正确加载(二进制!)PDF 文件的字节
  • “加密”是什么意思?如果文件以某种方式被加密,客户端会知道如何将其用作 PDF 文件吗?
  • @Lasse,filebytes 变量使用 GetStream() 方法存储编码值,该值将字符串变量传递给另一个函数。所以在这里我转换为字节[]。使用 .net mvc 中的上述代码成功下载了 pdf。这段代码我想转换 .net 核心。 Response.Outputstream 没有进入 .net 核心。

标签: c# asp.net-core-2.0


【解决方案1】:

@Luaan 先生已经给出了答案,但可能是我的代码也对你有帮助,所以我分享一下。

从文件夹下载 Pdf 文件

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

从数据库下载 pdf 文件

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

有关详细信息,另请参阅此问题和答案。 Return PDF to the Browser using Asp.net core

【讨论】:

  • 它工作正常。谢谢你的支持。 @Luaan 也感谢您的支持。
  • 非常欢迎先生,您真好,如果您对我的回答投赞成票,那将是我的荣幸。
【解决方案2】:

MVC 简化了这一点。您只需要一个返回ActionResult 的操作:

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

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

【讨论】:

  • @Luan,代码已执行但文件未下载。请提供任何其他解决方案。
  • @debugger 好吧,如果您只是在另一段 C# 代码中执行它,它不会做任何事情 - ActionResult 必须从某个端点返回。您的原始代码破解了请求管道并粗鲁地破坏了整个事情,因此您几乎可以在任何地方执行它,但这不适用于此代码。从控制器中的方法正确返回ActionResult 是否有问题?听起来您的 MVC 应用程序是旧 WebForms 应用程序的快速移植;您真的要避免以 MVC 方式执行此操作吗?
猜你喜欢
  • 2012-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
相关资源
最近更新 更多