I have a question about react. I need to download a file from the uploads/doc folder.
I've written my code, but it downloads an empty file. Could you give me a hint on how to fix this issue? Thank you so much!
if (result.isConfirmed) {
//console.log("error while downloading document: ");
await getDocfile(_id);
fetch('http://localhost:4200/uploads/docs')
.then(response => {
response.blob().then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = document_name + '.pdf';
a.click();
});
});
}
Related
Thanks in advance for taking a look. I am working on being able to download a zip file from react through a django api request. I am able to click on my pop up that downloads the zip file, but when I double click on the zip file to open, I get this error: "Unable to expand file_name.zip. It is an unsupported format" My response with the zip file seems to be passing correctly to the front end, so I am thinking it may be something wrong with the react code when making the "blob"? Thanks again.
Django code:
class DownloadZip(APIView):
def post(self, request, format=None):
# information to find file to create zip
profile_name = request.data["profile"]
profile_year = request.data["year"]
# file path to create zips from
path = str(Path(__file__).parent.resolve())
zip_dir = shutil.make_archive(profile_name + profile_year, "zip", path + "/" + profile_name + profile_year)
s = io.StringIO(zip_dir)
response = HttpResponse(s, content_type = "application/zip")
zip_name = profile_name + profile_year + ".zip"
response["Content-Disposition"] = f"attachment; filename={zip_name}"
return response
React code:
downloadZip = async () => {
const params = {
profile: this.state.profileName,
year: this.state.year,
};
axios({
url: `${serverUrl}/download_zip`,
method: "post",
data: params
}).then(
(res) => {
const url = window.URL.createObjectURL(new Blob([res.data],{type:'application/zip'}));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.zip');
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
},
(error) => {
console.log(error);
});
}
I did do a fellow commentor's suggestion, and updated to get route with query params, but am having the same issue. I can double click on the zip link on the web browser but a pop up appears "Unable to expand filename.zip. It is an unsupported format"
Please try adding {responseType: 'arraybuffer'}. I also had the same problem but after adding this {responseType: 'arraybuffer'}. I am getting correct file.
downloadZip = async () => {
const params = {
profile: this.state.profileName,
year: this.state.year,
};
axios.post(
`${serverUrl}/download_zip`,
params,
{
responseType: 'arraybuffer'
}
).then(
(res) => {
const url = window.URL.createObjectURL(new Blob([res.data],{type:'application/zip'}));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.zip');
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
},
(error) => {
console.log(error);
});
}
I am trying to download file but it is opening in new tab, but here I want to download file directly.
What I have tried
<a href={api_Url+'/SurveyImages/'+link} target = "_blank" download ={link}>{link}</a>
if I remove target = "_blank" then it replacing the file with my application tab.
How can I directly download it?
your code:
target = "_blank"
solution:
target = "_self"
Best solution as per new chrome specification https://developers.google.com/web/updates/2018/02/chrome-65-deprecations
Convert this code in React.
Vanilla JavaScript
public static downloadFile(url: string): void {
const xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = () => {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
const blobUrl = window.URL.createObjectURL(xmlHttp.response);
const e = document.createElement('a');
e.href = blobUrl;
e.download = blobUrl.substr(blobUrl.lastIndexOf('/') + 1);
document.body.appendChild(e);
e.click();
document.body.removeChild(e);
}
};
xmlHttp.responseType = 'blob';
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
}
If you're using angular try this.
async downloadBrochure(url: string) {
try {
const res = await this.httpClient.get(url, { responseType: 'blob' }).toPromise();
this.downloadFile(res);
} catch (e) {
console.log(e.body.message);
}
}
downloadFile(data) {
const url = window.URL.createObjectURL(data);
const e = document.createElement('a');
e.href = url;
e.download = url.substr(url.lastIndexOf('/') + 1);
document.body.appendChild(e);
e.click();
document.body.removeChild(e);
}
Click to download
This is not supported on all browsers: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a tags.
Try this:
axios({
url: 'http://localhost:5000/static/example.pdf',
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', 'file.pdf');
document.body.appendChild(link);
link.click();
});
Reference: https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743
You can try "HTML download Attribute"
https://www.w3schools.com/tags/att_a_download.asp
Download
I am trying to download a file using ReactJS. I have the link of the file and I can actually open the file through my browser. After several attempts. Here, is my function to download the file.
saveFile(filename) {
let blob = new Blob();
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
const a = document.createElement('a');
document.body.appendChild(a);
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 0)
}
}
Unfortunately, I get the pop-up as expected but I get a 0 MB file downloaded.
Any ideas on how to do around this? Note that the file is mp3
I am getting an html file from a backend application and now saving it in pdf format in react. However, unable to open it in adobe :(
CreateFile(data, contentType) {
let file;
if (contentType === "text/html") {
// file = new Blob([data], { type: contentType });
file = new Blob([new Uint8Array(data)], { type: contentType });
}
saveDocument() {
let contentType = "application/pdf";
let file = this.createFile(data,
contentType.toLowerCase());
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else { // others apart from Safari and Opera mini
var a = document.createElement("a"),
url = window.URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
can anyone help?
I suggest you using a library like wkhtmltopdf in your backend to convert the html into pdf before sending it.
I am using AngularJS and in POST request download file .xls
this.$http.post('/api/rept/detc/xls', params).then((response) => {
let blob = new Blob([response], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
}),
objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
})
But then download file without format with name (in this format: c65c45f8-e6a3-458d-xxxx-43c5fcxxxxx).
How can I download without FileSave package?
Similar approach that worked for me:
this.$http.post('/api/rept/detc/xls', params).then((response) => {
let blob = new Blob([response]);
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = 'filename_here';
a.target = '_blank';
a.click();
})