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

时间:2019-10-15 08:39:06

标签: vue.js

我正在尝试使用VueJs / Axios下载pdf文件,但出现一个空文件。使用C#创建时,流为111 kb,但返回到Vue.js时仅为300字节。

C#
   HttpResponseMessage httpResponse = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            httpResponse.Content = new StreamContent(ms);
            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
 createPdf: function () {
            var self = this;
            self.ShowSpinner = true;  
            axios({
                method: 'post',
                url: self.baseUrl + '/api/ChangeRequestReport/CreatePdf',
                responseType: 'blob',
                data: {
                    model: self.ChangeRequestReportModel                    
                }
            })
                .then(function (response) {
                    console.log(response);
                    //self.ChangeRequestReportModel = response.data;
                    const url = window.URL.createObjectURL(new Blob([response.data], { type: "application/pdf" }));
                    const link = document.createElement('a');
                    link.href = url;
                    link.setAttribute('download', 'test.pdf'); //or any other extension
                    document.body.appendChild(link);
                    link.click();
                    self.ShowSpinner = false;
                })
                .catch(error => {
                    console.log(error);
                    this.error = true;
                    alert("error");
                });

0 个答案:

没有答案