Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
How to download a file with a HTML button or Javascript?

There's a possible duplicate here, but I couldn't find my answer to any other question

I'm trying to download a file that comes from my API. My API endpoint returns me a content-type application/vnd.ms-excel and the structure of my file in the body of the response. The file comes like this:

Body of the response

When I try it on Postman and click in the option Save Response and then Save to a file, everything works perfectly.

But when I try it on my React App, the file comes with those strange characters from the body of the response, instead of saving it as Postman does. I've tried a lot of different ways to save it, but it still doesn't work. Those are 3 ways I already tried to trigger the file download:

try {  
    const response = await api.get(`/portfolio/files?portfolio_id=${wallet.id}&portfolio_filename=${file.name}`, {
        headers: {
            'x-access-token': localStorage.getItem('token')
        }
    });

    // 1st way
    const blob = new Blob([response.data], { type: response.headers['content-type'] });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = file.name.split['.'];
    link.click();
    
    // 2nd way
    const url = window.URL.createObjectURL(new Blob([response.data], { type: response.headers['content-type'] }));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', file.name);
    document.body.appendChild(link);
    link.click();
    
    // 3rd way
    const blob = new Blob([response.data], { type: "octet/stream" });
    fileSaver.saveAs(blob, file.name);

} catch(err) {
    console.error(err);
} 
    // 3rd way
    const blob = new Blob([response.data], { type: "octet/stream" });
    fileSaver.saveAs(blob, file.name);

} catch(err) {
    console.error(err);
}

I'm using a Blob to create a URL to my file, setting its content as the body of the response and its type as the content-type (which is application/vnd.ms-excel, like I said before). All those three ways always write those exact same symbols into the file, instead of downloading it normally, as Postman does.

Does anyone know what am I missing here?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!