简体   繁体   English

在客户端上下载Web API发送的pdf字节数组

[英]Download byte array sent by web api as pdf on client

I am exporting crystal report to a pdf document and there is a button in UI that downloads that pdf in "Downloads" folder. 我正在将Crystal报表导出为pdf文档,并且UI中有一个按钮可以在“下载”文件夹中下载该pdf。 To achieve this I have a method in web api that gets executed on button click and that method returns HttpResponseMessage whose contents are the byte array (the pdf resides on blob and I download that file to a byte array). 为此,我在Web api中有一个方法,该方法在单击按钮时执行,该方法返回HttpResponseMessage,其内容为字节数组(pdf驻留在blob上,我将该文件下载到字节数组)。 From UI, using window.open method of javascript I am directly opening the URL of the web api method which when executed downloads the file in downloads folder. 从UI,使用javascript的window.open方法,我直接打开Web api方法的URL,该URL在执行时会将文件下载到downloads文件夹中。

This works fine. 这很好。 But now I have added [Authorize] attribute to the web api controller and hence when javascript window opens with the method URL, user is prompted for a user name and password value. 但是现在我已经向Web api控制器添加了[Authorize]属性,因此,当使用方法URL打开javascript窗口时,系统会提示用户输入用户名和密码值。

I am trying to post an ajax request to the server which returns me byte array on client. 我试图将ajax请求发布到服务器,该请求将客户端上的字节数组返回给我。 After the ajax request is executed, I have written the code below: 执行ajax请求后,我编写了以下代码:

data = "data:application/octet-stream;base64," + data;
document.location = data;

The file does get downloaded but it gets downloaded as a "download" file for which I have to use "Open with.." option to view the file. 该文件确实已下载,但已作为“下载”文件下载,我必须使用“打开方式..”选项来查看该文件。 How can I download it as a pdf document ? 如何将其下载为pdf文档?

If you are trying to serve a file with WebApi, you can do this: 如果您尝试使用WebApi提供文件,则可以执行以下操作:

 HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
 Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true);
 response.Content = new StreamContent(fileStream);
 response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
 response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
 response.Content.Headers.ContentDisposition.FileName = "myfilename.pdf";

  return response;

You don't need to manually dispose the stream, the framework calls HttpResponseMessage.Dispose, which calls StreamContent.Dispose, which calls FileStream.Dispose. 您无需手动处理流,该框架调用HttpResponseMessage.Dispose,后者调用StreamContent.Dispose,后者调用FileStream.Dispose。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM