Download zip folder with REST request in javascript. React.js - javascript

I am sending request to download zip folder from server, which is sending me below response - (Zip folder in bytes)
PK�s�H test.txt~���T*-N-R�R*I-.Q���PK�/[�PK�s�Htest.txt���T*-N- R�R*I-.Q���PK�/[�PK�s�H�/[� test.txt~PK�s�H�/[�Ltest.txtPKm�
In react I have written below function to download the zip folder.I am getting error while extracting zip folder.
downloadUtmFile: function() {
function download(text, name, type) {
var a = document.createElement("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
a.click();
}
DashboardStore.downloadFile(API_ENDPOINT.utmFileDownload).then(function(result) {
download(result,'', 'application/zip');
}.bind(this), function(error) {
this.setState({
message: error
});
}.bind(this));
},
I am using Blob and passing it type as "application/zip"
While extracting the zip folder it is throwing me error.

I think this is the header's problem. Need to add the following thing in the request header,
{
"content-type": "application/zip",
responseType: "blob",
}

Related

How to download excel file with axios vuejs?

On the controller I return a path to where the excel file is located..Now I want to download that file
Below is my code:
reportExcel(val) {
axios
.get("/algn/api/report/" + val)
.then((res) => {
var url = res.data; // http://localhost.local/public/files/data.xlsx
const a = document.createElement("a");
a.href = url;
a.download = url.split("/").pop();
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
})
.catch((error) => {
console.log(error);
});
},
I am getting the error as "Excel cannot open the file "data.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". (The original excel file is still usable).
I have tried all the solutions which I found in google but nothing worked. Please help. Thanks
Try this:
reportExcel(val) {
axios
// add responseType
.get("/algn/api/report/" + val, {responseType : 'blob'})
.then((res) => {
const url = window.URL.createObjectURL(new Blob([res]));
const a = document.createElement("a");
a.href = url;
const filename = `file.xlsx`;
a.setAttribute('download', filename);
document.body.appendChild(link);
a.click();
a.remove();
})
.catch((error) => {
console.log(error);
});
},
Assuming the link gives correct excel file, we can inform that it is file (not the usual JSON) by specifying {responseType : 'blob'} in the request. Then, create the file using window.URL.createObjectURL(new Blob([res])). The rest is small adjustments to handle file instead of text.

File is not showing local language after downloading

I have an application which is developed with node.js and hosted on heroku. We are generating a pdf on the node.js server and sending the stream to frontend, so that the users can download the file.
When i am trying it on the localhost, i am able to see proper content in the file. But when i host the node.js code on heroku and try the same, the file is not showing local language(telugu, an indian language) in the pdf. Below is the screenshot of the file i am getting.
The below code is the frontend code which will hit the server api and get the file content from server
const response = await axios.post(
'/reports/pdf',
{ tests: this.tests },
{ responseType: 'blob' },
);
window.console.log(response);
if (response) {
this.createAndDownloadBlobFile(response, 'tests');
}
The below code is to download the file. This function is called in the above code after getting the response.
createAndDownloadBlobFile(body, filename, extension = 'pdf') {
const blob = new Blob([body]);
const fileName = `${filename}.${extension}`;
if (navigator.msSaveBlob) {
// IE 10+
navigator.msSaveBlob(blob, fileName);
} else {
const link = document.createElement('a');
// Browsers that support HTML5 download attribute
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', fileName);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
},
The node.js code is as below
return new Promise((resolve, reject) => {
pdf
.create(document, options)
.then((res) => {
var content = fs.readFileSync(path.resolve(__dirname, '../utils/output.pdf'));
resolve(content);
})
.catch((error) => {
reject(error);
});
});
I tried few different ways by changing the response format to base64 and changing the data format. But still no use. Any help would be really appreciated.

handling file download from api call

In react, I am testing my file download based on John Culviner's solution mentioned in this post
axios.post('api/downloadMyFile',
data
).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]))
const a = document.createElement('a');
a.href = url;
a.download = "test.zip"
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
}).catch((err) => {
}
So file test.zip is getting downloaded. but when I tried to open it after saving it I am getting Compressed Zip folder error in windows.
Also, I noticed that I don't need to specify the name of the file in the line a.download = "test.zip" because the webservice is getting the file from shared storage and it already has a name.
So in this case, do I need to have the filename also in the response object? something like response.filename so that I could use it in the following line instead of naming it manually:
a.download = response.filename
The response.data returned from Axios is a JSON string. So creating a Blob from that JSON doesn't produce the correct object. From the Axios docs:
// responseType indicates the type of data that the server will
respond with
// options are: 'arraybuffer', 'document', 'json',
'text', 'stream'
// browser only: 'blob'
responseType: 'json',
// default
The simple fix is to tell Axios to provide the response in the form of a Blob. Then the URL.createObjectURL() will produce a URL to a file that is in the correct format.
axios.post('api/downloadMyFile', data, { responseType: 'blob' })
.then(blob=>{
const url = window.URL.createObjectURL(blob.data);
const a = document.createElement('a');
a.href = url;
a.download = "download.zip"
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})

How download Excel file in Vue.js application correctly?

I'm struggling to download an Excel file in xlsx format in my Vue.js application. My Vue.js application make post request to the Node.js application which download that Excel file from remote SFTP server. Backend application works without any problems.
In Vue.js application I use next code:
axios.post(config.backendHost + '/excel', {
file_name: fileName
}).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', fileName)
document.body.appendChild(link)
link.click()
});
After downloading file by browser, file opens automatically and I am experiencing an error that looks like this:
We found a problem with some content .xlsx. Do you want us to try and recover as much as we can?
You need to add the response type as a third argument in your post call
{
responseType: 'blob'
}
Your final code like that
axios.post(config.backendHost + '/excel', {
file_name: fileName
}, {
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', fileName)
document.body.appendChild(link)
link.click()
});
Or you can use the library FileSaver.js to save your file
import FileSaver from 'file-saver'
axios.post(config.backendHost + '/excel', {
file_name: fileName
}, {
responseType: 'blob'
}).then((response) => {
// response.data is a blob type
FileSaver.saveAs(response.data, fileName);
});
my case worked:
axios.get(`/api/v1/companies/${companyId}/export`, {
responseType: 'blob',
}).then((response) => {
const url = URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute(
'download',
`${companyId}-${new Date().toLocaleDateString()}.xlsx`
)
document.body.appendChild(link)
link.click()
})

Download excel cannot open the file because the file format or file extension

const data = ('start_date=2019-07-04&end_date=2019-07-24');
axios({
url: `http://localhost:4000/report/data?${data}`,
method: 'GET',
responseType: "arraybuffer", // important
}).then(response => {
// BLOB NAVIGATOR
let blob = new Blob([response.data], { type: '' });
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob);
} else {
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.setAttribute('download', '');
document.body.appendChild(link);
link.download = [];
link.click();
document.body.removeChild(link);
}
});
I'm trying to download an xlsx file with reactJS but i'm receiving this message when i try to open my file after download:
"Excel can not open file 'file.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 file format"
Here's the frontend code:

Categories