user7889681
user7889681

Reputation:

Download file on clicking url

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

Answers (5)

Rock
Rock

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();
  1. Call that api form client by sending filename and path as attributes

Upvotes: 0

nanobar
nanobar

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

Mohammed Insaf M
Mohammed Insaf M

Reputation: 17

Do like this,

<a href={fileUrl}><button>Download</button></a>

Upvotes: 0

Rock
Rock

Reputation: 19

use window.open(fileUrl) - will download ;

Upvotes: 0

Quentin
Quentin

Reputation: 944443

Just link to it.

<a href={fileUrl}>Download</a>

Upvotes: 1

Related Questions