download file in react - reactjs

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

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

How to download multiple files with Axios?

async function download(stuff) {
if (stuff.length > 1) {
//What do I do?
} else if (stuff.length === 1) {
const link= stuff[0];
axios({
url: `/link`,
method: "GET",
responseType: "blob", // important
}).then((response) => {
let url = window.URL.createObjectURL(new Blob([response.data]));
let a = document.createElement("a");
a.href = url;
a.download = "myFile.jpg"
a.click();
});
}
}
I use this and it works fine when I want to download a single file. But if stuff contains more elements, I would like to download them all. One after another doesn't work well, as the user has to confirm them separately. So, I would like to download them all together as a zip file. Is there a recommended method how to do that?

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

Images not found for Dropbox login window

I have been implementing the Dropbox API and Dropbox Chooser into a React application. When I call 'oauth2/authorize' for the login page, I receive the correct HTML, but when I load it I receive 404 errors for all of the image files that would help style it. I attached a screenshot to show what the error looks like. Any idea why it's happening or how to fix it?
The call :
axios({
method: 'get',
url: 'https://www.dropbox.com/oauth2/authorize?client_id=' + APP_KEY + '&response_type=code',
headers: {
'Content-Type' : 'application/json' ,
'Authorization' : AUTH
}
}).then(function (res) {
let pretty = stringifyObject(res.data, {
singleQuotes: false
});
response.send(pretty);
})
.catch(function (error) {
response.send(error.response.data);
});
The fetch :
fetch(URL + '/api/login', {method: "GET"})
.then((res)=>{ return res.text() })
.then((text)=>{
let html = React.createElement('div',{dangerouslySetInnerHTML: {__html:text}});
})
You're downloading the data for Dropbox's /oauth2/authorize, but https://www.dropbox.com/oauth2/authorize is actually a web page, not an API call, so you should not be using your HTTPS client like this to download the HTML data.
You should instead be directing the user to that https://www.dropbox.com/oauth2/authorize... page in their browser. For example, you can construct the https://www.dropbox.com/oauth2/authorize... URL and then put it in an <a> HTML link for the user to click on, or redirect them there via JavaScript, depending on what makes sense for your use case.

How to show pdf file in react.js

i just try to sample application for ios, android and web using react-native-web. Here i have to download a pdf file from server and while click the showpdf button the downloaded file need to open in both android application as well as windows browser also. for browser download i have used the following code
fetch('http://www.pdf995.com/samples/pdf.pdf',{
method: 'GET',
mode: 'no-cors',
responseType: 'blob', // important
headers: {
'Content-Type': 'application/json',
},})
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', item.pdfFileName);
document.body.appendChild(link);
link.click();
this.setState({
pdf_url:url
});
after download i need to open this pdf file. please help if anyone know this. thanks.
You could use <iframe> to preview the PDF directly in your page, setting the src attribute to pdf_url. window.open(pdf_url) is also an option as mentioned above, but it'll require the user to have adblocker/pop-up blocker turned off.
In your render():
{pdf_url && <iframe src={pdf_url} />}
See MDN for multiple ways to display files
I suggest you to look at https://www.npmjs.com/package/react-pdf library, using which you can simply display pdfs just like images
Here is online demo http://projects.wojtekmaj.pl/react-pdf/

Resources