Download PDF file forcefully instead of opening new tab using javascript - javascript

Here's what i've done so far. I managed to download the file but it's giving me "object%200%object" on the url when i try to open the file.
fetch({
url,
method: 'GET',
responseType: 'blob', // important
contentDisposition: 'attachment',
contentType: 'application/pdf',
mode: 'no-cors'
})
.then(r => r.blob())
.then((response) => {
console.log(response);
const s = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.setAttribute('download', `test.pdf`);
link.click();
});

Related

React - the downloaded pdf is blank

At first, I send a GET request for the pdf data
const config = {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
baseURL: 'https://my-site.com',
};
const axiosInstance = axios.create({config});
const pdf = await axiosInstance.get('url', {
headers: { Authorization: 'Bearer ' + accessToken, Accept: '*/*' },
})
The value of pdf is the same as below
Then I tried to download the file
const url = window.URL.createObjectURL(new Blob([pdf]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `FileName.pdf`);
// Append to html link element page
document.body.appendChild(link);
// Start download
link.click();
I can download the pdf file successfully, but the pdf is blank when I open it.
How to fix it?
Fix it by adding responseType: 'blob'
const pdf = await axiosInstance.get('url', {
headers: { Authorization: 'Bearer ' + accessToken, Accept: '*/*' },
responseType: 'blob',
})

How to open PDF in a new tab from Cloud without downloading it in local machine

I am trying to open a PDF file in a new tab and want to read file without downloading it in local machine.
I tried this function, but it is not loading my pdf and giving error can not load pdf
function readFileInNewTab (fileId) {
let url = BASE_URL + "api/CMS/Documents/Download/" + fileId;
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/pdf', ...authHeader(url) },
credentials: 'include',
responseType: "blob", // important
};
inProgress = true;
return fetch (url, requestOptions).then(handleResponse)
.then((response)=> {
const file = new Blob([response], { type: "application/pdf" });
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
debugger
const pdfWindow = window.open();
pdfWindow.location.href = fileURL;
})
.catch((error) => {
console.log(error);
});
} ```

Excel file corrupted on download with axios vuejs

I am trying to download an excel file. I have used axios for it.
I have tried the below code
axios.post(backendURL + 'api/client?file_name='+file_name,params, {
file_name: file_name
}, {
responseType: 'blob'
}).then((response) => {
const url = URL.createObjectURL(new Blob([response.data], {
type: 'application/vnd.ms-excel'
}))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', file_name)
document.body.appendChild(link)
link.click()
});
I am getting the error as "Excel cannot open the file "filename.xlsx" because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file"
I have tried all the solutions which I found in google but nothing worked. Please help
downloadFile() {
axios({
url: this.scenario.file, //.substring(0, this.scenario.file.lastIndexOf("/"))
method: "GET",
headers: {"Accept": "application/vnd.ms-excel"},
responseType: "blob"
}).then(response => {
const fileURL = window.URL.createObjectURL(new Blob([response.data]));
const fileLink = document.createElement("a");
fileLink.href = fileURL;
fileLink.setAttribute("download", "file.xlsx");
document.body.appendChild(fileLink);
fileLink.click();
});
},

Download PDF from http response with Axios

I am working on a Vue application with a Laravel back-end API. After clicking on a link I would like to do a call to the server to download a certain file (most of the time a PDF file). When I do a get request with axios I get a PDF in return, in the body of the response. I would like to download that file directly.
To give you a better view of how the response is looking like:
(note: I know a real text response is better than an image but I don't see any way to return that because of the length of the actual PDF content..)
Is there any way of downloading that file with JavaScript or something? It has to be specific a direct download without clicking on the button again.
Code
// This method gets called when clicking on a link
downloadFile(id) {
const specificationId = this.$route.params.specificationId;
axios
.get(`${this.$API_URL}/api/v1/suppliersmanagement/product-specifications/${specificationId}/fileupload/${id}/download`, {
headers: this.headers,
})
.then(response => {
console.log(response);
// Direct download the file here..
})
.catch(error => console.log(error));
},
As #Sandip Nirmal suggested I've used downloadjs and that worked out pretty good! Had to make a few adjustments to my code but in the end it worked out.
My new code
// npm i downloadjs
import download from 'downloadjs'
// method
downloadFile(file) {
const specificationId = this.$route.params.specificationId;
axios
.get(`${this.$API_URL}/api/v1/suppliersmanagement/product-specifications/${specificationId}/fileupload/${file.id}/download`, {
headers: this.headers,
responseType: 'blob', // had to add this one here
})
.then(response => {
const content = response.headers['content-type'];
download(response.data, file.file_name, content)
})
.catch(error => console.log(error));
},
You should use 'responseType' option. For example:
axios.get(
url,
{responseType: 'blob'} // !!!
).then((response) => {
window.open(URL.createObjectURL(response.data));
})
You have 2 options for this. If you want to do it from server and if you are using Node.js as a backend. You can do it easily using res.download method of express. You can follow this answer for that Download a file from NodeJS Server using Express.
But if you want to handle it from client then there are few options since you can't use axios, XHR, fetch to download file directly. You can either use download.js or write your own code in following way.
return axios({
url: '/download', // download url
method: 'get',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
mode: 'no-cors'
}
})
.then(response => response.blob())
.then(blob => {
var url = window.URL.createObjectURL(blob)
var a = document.createElement('a')
a.href = url
a.download = fileName
a.click()
a.remove()
setTimeout(() => window.URL.revokeObjectURL(url), 100)
})
Since response returned from server is in json format you need to convert it into ObjectURL and set it to anchor tag.
If you sneak inside download.js code you will find same implementation.
2022 answer: using node.js, fs.promises and async/await
The key is using responseType: 'stream' per the Axios docs.
import axios from 'axios';
import { writeFile } from 'fs/promises';
const downloadFile = async () => {
const response = await axios.get('https://someurl', {
params: {
// ...
},
// See https://axios-http.com/docs/api_intro
responseType: 'stream',
});
const pdfContents = response.data;
await writeFile('file.pdf', pdfContents);
};
You can do it like this
download(filename) {
fetch(url , { headers })
.then(response => response.blob())
.then(blob => URL.createObjectURL(blob))
.then(uril => {
var link = document.createElement("a");
link.href = uril;
link.download = filename + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
}
here I want to download a CSV file, So I add .csv to the filename.
const downloadPDF = (id, fileName) => {
axios({
method: 'get',
url: `https://api.example.com/pdf/invoice/${id}`,
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('token'),
'Content-Type': 'application/json'
},
responseType: 'blob'
}).then(function (response) {
const a = document.createElement('a');
a.href = window.URL.createObjectURL(response.data);
a.download = `${fileName}.pdf`;
document.body.appendChild(a);
a.click();
a.remove();
});
}

Get binary data with XMLHttpRequest in a Firefox extension with AXIOS

I am trying to download binary data from Firefox browser. My app is based on react and redux and using axios as my HTTP client.
I have to send
xhr.open() before responseType= arraybuffer
Below implementation didnt work
axios({
url:`http://api.demo6.test.com:8080/resources/v1/${dObj.payload.surveyId}`,
responseType: 'arraybuffer',
method: 'post',
data: dObj.payload.filterData,
headers: {
"Accept": "application/vnd.ms-excel",
"Content-Type": "application/json",
"X-Bazaarify-Session-Token": "cfff-7-07f13399abed" //token
}
}).then(function(response) {
// const y = yield put(surveyResponseDowloadComplete({
// data: response.data
// }));
let blob = new Blob([response.data], {type: "application/vnd.ms-excel"});
let link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = "test.xls";
link.click();
console.log(response);
//response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
How can I do it with axios?
This is a simple saga that downloads binary data using axios:
function * downloadFileSaga(url) {
const response = yield axios.get(url, {
responseType: 'arraybuffer'
})
console.log(response.data); // arraybuffer
}
You can then use Blob or FileReader to work with the arraybuffer further.
Example: https://codesandbox.io/s/n7kmvjr49m

Categories