Is there way a to work a download functionality using react without having to put resources (in my case, zip files) in the public folder? For example:
<a href='/somefile.txt' download>Click to download</a>
This works as long as "somefile.txt" is included in the public folder, if I wanted serve "somefile.txt" from backend (express.js) then make it downloadable through a link in frontend, how would I go about that?
I tried this:
//backend
app.get('/download/:id', (req, res) => {
const file = req.params.id;
res.download(path.join(__dirname,"downloadable", file+".zip"),function(err)
{
if(err) console.log(err);
console.log("downloaded")
});
});
//frontend
const tryDownloadOne = (url, filename) => { //using js-file-download library
axios.get(url, {
responseType: 'blob',
})
.then((res) => {
fileDownload(res.data, filename)
})
}
const tryDownloadTwo = async(url,fileName)=>{ //creating dummy anchor tag
const response = await axios.get(url, { responseType: 'blob' });
if (response.data.error) console.error(response.data.error)
const fileURL = window.URL.createObjectURL(new Blob([response.data]));
const fileLink = document.createElement('a');
fileLink.href = fileURL;
console.log(response.headers["content-disposition"]);
fileLink.setAttribute('download', fileName);
document.body.appendChild(fileLink);
fileLink.click();
fileLink.remove();
}
const tryDownloadThree=async(url,fileName)=>{ //using file saver library
const res=await fetch(url);
const blob=await res.blob();
saveAs(blob, fileName);
}
I tried 3 different methods in the frontend ,they work on desktop browsers but don't on some mobile browsers e.g Ucbrowser and Opera mini. Is there a more compatible approach ?