C# VueJs/Axios-如何在浏览器中从API调用下载pdf文件
我可以让Axios在浏览器上下载pdf文件,pdf中每个页面的页数/页面方向正确,但内容为空 这是我的API:C# VueJs/Axios-如何在浏览器中从API调用下载pdf文件,c#,api,vue.js,download,axios,C#,Api,Vue.js,Download,Axios,我可以让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(d
[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) {
});
它现在正在按预期工作。因此,它似乎与声明响应类型有关:)您是否使用asp.net核心作为api?否,.net 4.7.1:)