如何在Asp.net CORE MVC中的浏览器上下载PDF文件
我正在使用下面的代码,这些代码用于以pdf格式下载SSRS报告:
I am using below code which used to download SSRS report in pdf format:
string URL = "http://ssrs-test.com/ReportS/?/UAT_FOLDER";
URL = URL + "&SRNo=122&rs:Command=Render&rs:Format=pdf";
System.Net.HttpWebRequest Req = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(URL);
Req.Method = "GET";
string path = @ "E:\New folder\Test.pdf";
System.Net.WebResponse objResponse = Req.GetResponse();
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create);
System.IO.Stream stream = objResponse.GetResponseStream();
byte[] buf = new byte[1024];
int len = stream.Read(buf, 0, 1024);
while (len > 0) {
fs.Write(buf, 0, len);
len = stream.Read(buf, 0, 1024);
}
stream.Close();
fs.Close();
哪个可以在指定的路径E:\New folder\
中完美创建一个pdf文件,我想做的是:
Which perfectly creates a pdf file in the specified path E:\New folder\
, what I am trying to do is:
我需要像在asp.net中一样使用Response.Write()
和Response.End()
等在浏览器中下载它.
I need download it on browser as we were doing in the asp.net with Response.Write()
and Response.End()
etc.
我可以在ASP.Net Core中做同样的事情吗?
Can I do the same in the ASP.Net Core?
我尝试过的内容:
return new PhysicalFileResult(@"with_samplepdf_file", "application/pdf"); -- Not worked
var stream = new FileStream(@"with_samplepdf_file", FileMode.Open);
return new FileStreamResult(stream, "application/pdf"); -- Not worked - Nothing happening on the browser
var file = @"with_samplepdf_file/pdf";
// Response...
System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
{
FileName = file,
Inline = displayInline // false = prompt the user for downloading; true = browser to try to show the file inline
};
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.Headers.Add("X-Content-Type-Options", "nosniff");
return File(System.IO.File.ReadAllBytes(file), "application/pdf");
首先,您需要确保已在项目中上传了文件.
First,you need to be sure that you have uploaded the file in your project.
这是一个有关如何在Asp.Net Core中的浏览器上下载pdf的简单演示:
Here is a simple demo about how to download pdf on the browser in Asp.Net Core:
1.视图:
<a asp-action="GetPdf" asp-controller="Users">Download</a>
2.Controller(确保文件已存在于wwwroot/file
文件夹中):
2.Controller(be sure that the file have been exsit in wwwroot/file
folder):
[HttpGet]
public ActionResult GetPdf()
{
string filePath = "~/file/test.pdf";
Response.Headers.Add("Content-Disposition", "inline; filename=test.pdf");
return File(filePath, "application/pdf");
}
3.Startup.cs:
3.Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseStaticFiles();
//...
}
4.结果: