CRo*_*rts 2 c# api download vue.js 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(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;
}
Run Code Online (Sandbox Code Playgroud)
然后我的 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) {
});
},
Run Code Online (Sandbox Code Playgroud)
然后下载该文件,但内容为空。
我发现通过改变我的 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) {
});
Run Code Online (Sandbox Code Playgroud)
现在它正在按预期工作。所以看起来它与声明响应类型有关:)
| 归档时间: |
|
| 查看次数: |
5186 次 |
| 最近记录: |