How to initiate a download via a GET request in axios

I am currently utilizing Vue.js 2 with Axios to send a GET request and pass parameters to the server in order to retrieve a PDF as a response. The server is powered by Laravel.

Having issues with force downloading the PDF even though the correct headers are being returned from the server.

This scenario is common when generating a PDF report and sending filters to the server. How can this be achieved effectively?

Update

I have found a solution that works using raw XHR object instead of Axios. By creating a blob object and utilizing the `createUrlObject` function, I was able to successfully download the PDF file. Here's a sample example:

let xhr = new XMLHttpRequest()
xhr.open('POST', Vue.config.baseUrl + `order-results/${id}/export-pdf`, true)
xhr.setRequestHeader("Authorization", 'Bearer ' + this.token())
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xhr.responseType = 'arraybuffer'

xhr.onload = function(e) {
  if (this.status === 200) {
    let blob = new Blob([this.response], { type:"application/pdf" })
    let link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = 'Results.pdf'
    link.click()
  }
}

Important: ensure that the responseType is set to array buffer

However, when attempting the same code with Axios, the returned PDF file is empty:

axios.post(`order-results/${id}/export-pdf`, {
  data,
  responseType: 'arraybuffer'
}).then((response) => {
  console.log(response)

  let blob = new Blob([response.data], { type: 'application/pdf' } ),
      url = window.URL.createObjectURL(blob)

  window.open(url);
})

Answer №1

When you receive an empty PDF file, it's likely because no data is being passed to the server. To rectify this, you can transmit data using a data object as shown below:

  axios
    .post(`order-results/${id}/export-pdf`, {
      data: {
        firstName: 'Fred'
      },
      responseType: 'arraybuffer'
    })
    .then(response => {
      console.log(response)

      let blob = new Blob([response.data], { type: 'application/pdf' }),
        url = window.URL.createObjectURL(blob)

      window.open(url) // I tried various methods like link.click, iframe, and others while experimenting with different approaches
    })

I must express my gratitude for giving me the hint on how to download a PDF from the response. Thank you so much :)

                var dates = {
                    fromDate: 20/5/2017,
                    toDate: 25/5/2017
                }

This is how I implemented it:

axios({
  method: 'post',
  url: '/reports/interval-dates',
  responseType: 'arraybuffer',
  data: dates
}).then(function(response) {
  let blob = new Blob([response.data], { type: 'application/pdf' })
  let link = document.createElement('a')
  link.href = window.URL.createObjectURL(blob)
  link.download = 'Report.pdf'
  link.click()
})

Answer №2

Give this a try: I've had great success with this code snippet, especially when dealing with compatibility issues in Internet Explorer 11 (keep in mind that createObjectURL doesn't function on Explorer 11)

axios({
  url: 'http://vvv.dev',
  method: 'GET',
  responseType: 'blob', // make sure to include this
}).then((response) => {
  if (!window.navigator.msSaveOrOpenBlob){
    // BLOB NAVIGATOR
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'download.pdf');
    document.body.appendChild(link);
    link.click();
  }else{
    // BLOB FOR EXPLORER 11
    const url = window.navigator.msSaveOrOpenBlob(new Blob([response.data]),"download.pdf");
  }
});

Visit this link for more information and examples

Answer №3

After trying various methods mentioned earlier, I encountered a popup block warning issue in my browser. Fortunately, the following code snippet resolved the problem for me:

axios.get(url, {responseType: 'arraybuffer'})
   .then(function (response) {
     var headers = response.headers();
     var blob = new Blob([response.data],{type:headers['content-type']});
     var link = document.createElement('a');
     link.href = window.URL.createObjectURL(blob);
     link.download = "Your_file_name";
     link.click();
});

Answer №4

It seems like achieving this functionality using axios or AJAX is not feasible. The file must remain in the browser's memory as saving it to disk is not allowed due to security reasons. JavaScript does not have the capability to interact with the disk, which is restricted by major browsers for security purposes.

One alternative method is to construct the URL on the front-end and trigger a download as shown below:

 var url = 'http://example.com/order-details/' + orderId + '/export-pdf?' + '..parameters..' 

 window.open(url, '_blank');

I hope you find this solution helpful!

Answer №5

Here is a piece of code that has been effective for me:

const request = new XMLHttpRequest();
request.open('POST', Vue.config.baseUrl + `order-results/${id}/export-pdf`, true);
request.setRequestHeader("Authorization", 'Bearer ' + this.token());
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.responseType = 'arraybuffer';
request.send();
request.onload = function(e) {
    if (this.status === 200) {
        const blob = new Blob([this.response], { type: "application/pdf" });
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = 'Results.pdf';
        link.click();
    }
}

}

Answer №6

Dealing with the same problems led me to generate a link and obtain the file through that method.

For further insight into my process, refer to the response posted on a different stackoverflow thread.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Foreach to reference data as "this"

I am attempting to iterate through this information in order to assign a value to each. const keys = Object.keys(response.data) keys.forEach((index, element) => { // let query = "this."+element this[element] = response.data[element] }); The de ...

Turn off the background when the automatic popup box appears

I have implemented a popup box that automatically appears after 5 seconds when the site is loaded. However, if I click outside of the popup box, it closes. I want to disable the background when the popup box is displayed. If I remove the two lines of code ...

Error encountered when using the module export in Node.js

I have a file named db.js which contains the following code: var mysql = require('mysql2'); var mysqlModel = require('mysql-model'); var appModel = mysqlModel.createConnection({ host : 'localhost', us ...

Navigating through search results on an XML page using jQuery

Context: I am currently facing a challenge involving the integration of Google search outcomes into a webpage I'm constructing. These findings are presented in XML format. My current approach to importing the XML is as follows: if (window.XMLHttpReq ...

Utilizing AngularJS to Retrieve Row Information Upon Button Selection

I'm currently developing an application that includes a feature allowing users to run a query from a drop-down menu and view the data in a table. Each row in the table will have a button, and when clicked, I need to capture the values of that specific ...

Tips for utilizing date objects instead of date 'strings' while still obtaining the desired outcome

Below is a schema that I am working with: var MySchema = new Schema ({ event: { full: String, date: String, name: String, } }); To illustrate, here are some examples of the values: event.date = '16/02/20 ...

Performing addition in Angular 2 with the help of TypeScript

Here is a code snippet of a component I have written: export class AppComponent { public num1: number = 2; public num2: number = 3; public sum: number = 0; public add() { this.sum = this.num1 + this.num2; } } However, when I r ...

Using NodeJS and Express together with Ajax techniques

I am currently developing a web application that utilizes Ajax to submit a file along with some form fields. One unique aspect of my form is that it allows for dynamic input, meaning users can add multiple rows with the same value. Additionally, the form i ...

Is it possible to pass an HTML element's id attribute to a function in JavaScript?

In the following code snippet, I am looking to send the id=content to the function mr and then display the result in the passed id=result. While this functionality is currently limited to this HTML file, I aim to extend it to other HTML pages by adding the ...

Embed a Link Fill Script into an Input Form

I have a program that automatically inserts specific links into an input form when clicked. However, I am encountering a problem. For some reason, I instructed the links to use the class linkText and specified certain values to be shown in the input text ...

Tips for setting up a webpacked vue.js application with an express/koa backend!

Struggling with setting up a vue.js project for easy debugging in combination with a koa server? The cross-env NODE_ENV=development webpack-dev-server --open --hot command from the webpack-simple generated configuration looks promising, but how should it b ...

What is the significance of incorporating vinyl-source-stream into gulp in my workflow?

Recently, I've been experimenting with gulp and browserify to convert my .jsx files into .js files. var gulp = require('gulp'); var browserify = require('browserify'); var reactify = require('reactify'); gulp.task(&apos ...

Mongoose Raises an Error When a Nonexistent Key is Detected

I am currently working on a code where I update my schema object with the request body. I have validation rules set up on the schema, but I'm facing an issue. I want the schema to throw an error when there is a non-existing field in the request body. ...

Contrasting the addition of an onClick listener through Jquery versus utilizing an HTML onclick attribute

I found this interesting piece of code that I want to share with you all: <!DOCTYPE html> <html> <head> <script type="text/javascript" src="jquery-1.12.4.js"></script> <title> HelloWorld JQuery </t ...

Can you always rely on promises being fulfilled?

Consider a scenario where we have a function named logData to handle HTTP requests and another function called logIntoDatabase. async logIntoDatabase(message) { ... } async logData(request, response) { await logIntoDatabase("something happened"); ...

The absence of a defined window - react-draft-wysiwyg integration with Next.js (SSR) is causing issues

Currently, I am in the process of developing a rich text editor that is used to convert plain HTML into editor content using Next.js for SSR. While working on this project, I encountered an error stating "window is not defined," prompting me to search for ...

"How can I open a DOCX file in a new window using JavaScript and then close the window

When attempting to open a doc/docx file in Word from an HTML link, my goal is to prevent the opening of a new browser window. First attempt: mywin=window.open("filename.docx","viewer"); The first attempt works fine, but it results in opening a new "view ...

Receiving an error message stating "Uncaught SyntaxError: Unexpected token <" in React while utilizing the AWS SDK

Each time I execute 'npm run build' in main.js, an error keeps popping up: Uncaught SyntaxError: Unexpected token < The error vanishes after refreshing the page. Upon investigation, I discovered that two libraries are causing this problem: ...

Jquery vertical menu with a dynamic sliding animation from the right side to the left side

Hello everyone, I am looking to have my vertical menu slide from right to left instead of the typical top to bottom sliding that comes with using .toggle() in jQuery. Specifically, when the hamburger menu is clicked, I want the menu to slide out from right ...

Determining If Props Have Been Undefined In React

Greetings and thank you for taking the time to read this: I am currently working through a tutorial that can be found here: My issue lies in the creation of an author, where the application is trying to load the URL of the current author's ID, which ...