从字节下载PDF文件[]

时间:2019-08-05 07:09:13

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

我一直在努力从ASP.Net MVC C#中的$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $cat = ( isset( $_GET['category_select'] ) ) ? $_GET['category_select'] : 1; $args = array ( 'cat' => $cat, 'posts_per_page' => 10, 'paged' => $paged ); $query = new WP_Query( $args ); if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post(); echo "--------------------<br>"; echo "<br>" . the_title(); echo "<br>" . the_category(); endwhile; else: ?> <p>no results found.</p> <?php endif; wp_reset_postdata();?>下载PDF文件。下面的代码工作正常。

对于相同的bytes[]下载过程,我需要将代码转换为.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(); 。我收到一个错误: OutputStream 方法不包含此 ms.WriteTo(Response.OutputStream)行的响应。 预先谢谢。!

2 个答案:

答案 0 :(得分:2)

MVC对此进行了简化。您需要做的是返回ActionResult的操作:

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

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

答案 1 :(得分:0)

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

从文件夹下载Pdf文件

const player = jchannel.play('./Pascal.mp3')
                        ^
TypeError: jchannel.play is not a function

从数据库下载pdf文件

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

有关更多信息,请参见此问题和解答。 Return PDF to the Browser using Asp.net core