Reputation:
I have a absolute file url.
let fileUrl="https://xyz.blob.core.windows.net/aggregator/merchant/docs/45.txt?st=2018-06-11T10%3A09%3A43Z&se=2018-06-12T10%3A09%3A43Z&sp=r&sv=2017-04-17&sr=c&sig=ugiw0CuNXr0".
On clicking of a button, this file needs to get downloaded.
<button onClick={()=> {}>Download</button>
How can I achieve this using reactjs?
Upvotes: 2
Views: 8309
Reputation: 19
Okay to be precise you can follow below steps (this is in java) 1. Write new api which reads file into ByteArrayOutputStream and set the proper response type (File name and path will be requsted by Client) Eg :
ByteArrayOutputStream baos = dao.readFIle(filename, filepath);
String filename = filename+"."+fileextension;
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
response.setContentType("application/zip");
response.getOutputStream().write(baos.toByteArray());
response.flushBuffer();
baos.close();
Upvotes: 0
Reputation: 66445
A better way would be to not do it programatically:
<a href={fileUrl} download>
Download
</a>
If you want to go down the dark route of making it compatible on more browsers you need to fetch the file via ajax, create a blob, create a url from the blob, create an anchor element and assign the blob url, then trigger a click on it.
Or as @Quentin says if cross-origin is blocked then I would prefer to proxy to the file via your server on the same domain and still use the download attribute href="/api/fileproxy?url=http://...."
.
Upvotes: 1
Reputation: 17
Do like this,
<a href={fileUrl}><button>Download</button></a>
Upvotes: 0