download a file from AWS S3 URL using axios response [VueJs] - reactjs

So i have achieve to get the file URL from s3 bucket with axios and in console i can click the url and it will download the file, my question is how to achieve it without click the url from console? so when i press the download button from client it will also proceed to auto click the url as a response
this is what shown in the console img
here is my code to get the url :
exportProductPrice(priceSetID, productSalability, productCategoryStatus) {
this.$http.get("/price/product_price/export?export=1", {params:{
// embeds:'price_set_id,product.salability,product.category.status',
conditions: priceSetID + productSalability + productCategoryStatus
}}).then(response => {
console.log(response.data.file,'hit')
var fileURL = window.URL.createObjectURL(new Blob([responses.data]));
var fileLink = document.createElement('a');
fileLink.href = fileURL;
fileLink.setAttribute('download');
document.body.appendChild(fileLink);
fileLink.click();
}).catch((err) => {
return Promise.reject({ Error: 'something went wrong', err});
});
},

Related

How can i download excel file with using Flask and React?

I am trying to download xlsx file. I post an id and using it to get data from database. Then i can create an excel file but i couldn't download it.
My backend codes:
from flask import Flask
from flask import request, jsonify, make_response, json, send_file, redirect, url_for,send_from_directory
from bson.json_util import dumps
from flask_cors import CORS
import dbConnections.Test as db
import os
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}}, support_credentials=True)
#app.route("/test-report", methods=["POST"])
def downloadTestReport():
req = request.get_json();
results = db.GetTestResult(req)
return send_file('foo.xlsx', as_attachment=True)
if __name__ =="__main__":
app.run(debug=True)
And my frontend codes:
let downloadReport = (e)=>{
if(e.field ==="downloadReport"){
const objId= {testId: e.row.objId};
axios.post('http://127.0.0.1:5000/test-report', objId)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
The result on my console:
I wanna download excel file which is return.
To show what Ethan's comment is in code, Assuming your backend flask code is sending the Excel file as it should, your frontend code should look like this:
axios('/test-report', {
method: 'GET', //Pretty sure you want a GET method but otherwise POST methods can still return something too.
responseType: 'blob', // important
}).then((response) => { //Creates an <a> tag hyperlink that links the excel sheet Blob object to a url for downloading.
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `${Date.now()}.xlsx`); //set the attribute of the <a> link tag to be downloadable when clicked and name the sheet based on the date and time right now.
document.body.appendChild(link);
link.click(); //programmatically click the link so the user doesn't have to
document.body.removeChild(link);
URL.revokeObjectURL(url); //important for optimization and preventing memory leak even though link element has already been removed. In the case of long running apps that haven't been reloaded many times.
});
This is in reference to:
//https://stackoverflow.com/questions/41938718/how-to-download-files-using-axios?noredirect=1&lq=1
How to download excel in response from api react.js

REACT: download a file with Axios using a progress bar

I have an application that downloads a zip file in this way. It works regularly but when clicked, the download is performed in the background and the browser shows the actual download of the file only when the whole stream has been downloaded locally. So if the file takes 1 minute to download, the user doesn't understand what the site is doing. Is there any way to show a progress bar?
await axios({
url: sUrl,
method: "GET",
responseType: "blob" // important
})
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", fname); //or any other extension
document.body.appendChild(link);
link.click();
this.setState({ downloading: false });
})
.catch(error => {
this.setState({ downloading: false });
message.warn("Errore: " + error.message);
return [];
});
Yes, you can achieve this by using onDownloadProgress method provided by axios package, check the below example :
await axios({
url: sUrl,
method: "GET",
responseType: "blob", // important
onDownloadProgress: (progressEvent) => {
let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); // you can use this to show user percentage of file downloaded
}
})
Axios package has both onDownloadProgress and onUploadProgress to show a progress bar during download or upload, have you tried them?
I recommend you to have a quick look at this Tutorial

Axios IE 11 issue, cannot download response type blob

axios.get("http://localhost:63542/api/v1/WorkInst",
{
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/pdf'
}
})
.then((response) => {
console.log(response);
var blob = new Blob([response.data], {type: 'application/pdf'});
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href= downloadUrl;
a.download = ("test.pdf");
a.click();
})
.catch((error) => console.log(error));
But instead of downloading, "Do you want to allow this website to open an app on your computer?" But it is working using google chrome and mozilla firefox. Badly need help on this
As far as I know, the Download attribute not support IE browser. So, in the IE and Edge browser, after getting the file data, you could use the msSaveOrOpenBlob method to download the file in IE and Edge browser, and in the Chrome or Firefox browser, you could create a hyperlink to download the file using the URL. More detail information, please check this sample:
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
//IE11 and the legacy version Edge support
console.log("IE & Edge");
let blob = new Blob([data], { type: "text/html" });
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {// other browsers
console.log("Other browsers");
var bl = new Blob([data], { type: "text/html" });
var a = document.createElement("a");
a.href = URL.createObjectURL(bl);
a.download = fileName;
a.hidden = true;
document.body.appendChild(a);
a.click();
}

download file in react

i have an Restful API i created using Laravel, this API like this:
http://127.0.0.1:8000/api/file/pdf/{id}
and this is my code for download:
public function pdfDownload($id){
$pdf = Cv::findOrfail($id);
return Storage::download('public/pdf/'.$pdf->pdf);
}
it is worked in postman, and also in browser, it is directly download the file,
but with react.js, it is not work, this my code in react:
pdfDownload = (id) => {
fetch(' http://127.0.0.1:8000/api/file/pdf/' + id, {
method: 'get',
headers: {
Accept: 'application/octet-stream',
'Content-Type': 'application/octet-stream'
}
}).then((res) => res.json());
};
and i call this function in button like this :
<Button color="primary" onClick={() => this.pdfDownload(data.id)}>
Download
</Button>
the id is corrected, i am ensure from this, my question is how can i download file when click this button.. Thans...
XHR calls can not trigger file download, the way browser handles it. You will have to mimic a file download using javascript code yourself, using something like below:
Reference
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
Or use File Saver package, if you don't mind an extra dependency.
FileSaver Npm

How to show file upload progress for each file with AWS Javascript SDK?

I am trying to upload file to AWS S3 and its working fine. But when the file upload is going on for multiple files , how do i get the progress for each file. Below is my code in AngularJs
upload: function (file) {
options = {
accessKeyId : 'xxxxxxx',
secretAccessKey : 'xxxxxxxxxxxxxxxxxxxxxxx',
region : 'xxxxxx'
}
var s3 = new AWS.S3(options);
var params = {
Bucket : bucketStructure,
Key: file.name,
ContentType: file.type,
Body: file,
ServerSideEncryption: 'xxxx',
ACL : 'private'
};
s3.putObject(params, function(err, data) {
if(err) {
// There Was An Error With Your S3 Config
alert('AWS Error : '+err.message);
return false;
}
else {
// Success!
alert('Upload Done');
}
})
.on('httpUploadProgress',function(progress) {
//console.log(Math.round(progress.loaded / progress.total * 100) + '% done');
});
}
I am calling the above code which is in a service function, in a loop. So when the user clicks on form submit button, i get the two files to upload and in a loop below i am calling the above function:
angular.forEach($rootScope.awsfiles, function (file) {
FileFactory.Upload(file);
});
Now how do i get to know for which file the progress to show ?? Any other better ideas to get this working?? Thanks!

Resources