gpt4 book ai didi

c# - VueJs/Axios - 如何通过 API 调用在浏览器中下载 pdf 文件

转载 作者:行者123 更新时间:2023-12-03 08:54:25 25 4
gpt4 key购买 nike

我可以让axios在浏览器上下载pdf文件,并且pdf中每页的页数/页面方向是正确的,但内容是空的。

这是我的 API:

[HttpGet]
[Route("~/api/Document")]
public HttpResponseMessage Get(int id)
{
var dataBytes = File.ReadAllBytes("c:\\temp\\test.pdf");

var stream = new MemoryStream(dataBytes);

HttpResponseMessage httpResponse = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
httpResponse.Content = new StreamContent(stream);
httpResponse.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponse.Content.Headers.ContentDisposition.FileName = "test";
httpResponse.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

return httpResponse;
}

然后我的 vue js axios 调用:

test: function () {
var self = this;
var uri = '/api/Document';
axios.get(uri)
.then(function (response) {
console.log(response);
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'test.pdf'); //or any other extension
document.body.appendChild(link);
link.click();
})
.catch(function (error) {

});
},

然后下载文件,但内容为空。

最佳答案

我发现通过更改我的 Axios 方法来使用此

axios({
url: uri,
method: 'GET',
responseType: 'blob', // important
}).then(function (response) {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'test.pdf');
document.body.appendChild(link);
link.click();
})
.catch(function (error) {

});

它现在正在按预期工作。所以看起来它与声明响应类型有关:)

关于c# - VueJs/Axios - 如何通过 API 调用在浏览器中下载 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56703201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com