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

时间:2019-06-21 12:09:47

标签: 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(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) {

                });
            },

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

1 个答案:

答案 0 :(得分:0)

我通过更改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) {

                });

它现在正在按预期方式工作。因此,看起来与声明响应类型有关:)