VueJs/Axios - How to download pdf file in browser from API call

Viewed 3925

I am able to get Axios to download a pdf file on the browser, and the number of pages/page orientation of each page in the pdf is correct, but the content is empty.

This is my 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;
    }

and then my vue js axios call:

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) {

                });
            },

And this then downloads the file, but the content is empty.

1 Answers

I have found by changing my Axios method to use this

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) {

                });

It is now working as expected. So looks like its to do with declaring the response type :)

Related