I am trying to use ajax request to do a download for my file. This is my code:
const downloadFile = (element) => {
$.ajax({
url: element.id,
type: 'GET',
success: (result) => {
window.location=element.id;
},
error: (request,msg,error) => {
alert(request.responseText);
}
})
}
And HTML element:
'<td>' + `<a id=hiddenAPIRoute href="#" onclick="downloadFile(this)">Download</a>` + '</td>' +
I am able to download but it does a double download. I like using ajax so I can have better error handling. I am aware of the download attribute of html 5 but I want to include an alert for users to view if the file is not accessible.
2
Answers
You could use
fetch
andURL.createObjectURL
for your workflow. And move your api url todata-href
, usingid
is weird, it’s for another purpose:In error handling you can do like this and show the error response however you like:-