admin管理员组

文章数量:1406942

I have a absolute file url.

let fileUrl=".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?

I have a absolute file url.

let fileUrl="https://xyz.blob.core.windows/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?

Share Improve this question edited Jun 11, 2018 at 10:41 asked Jun 11, 2018 at 10:15 user7889681user7889681 5
  • <a href="xyz.blob.core.windows/aggregator/merchant/docs/…" >Download</a> – Sakkeer A Commented Jun 11, 2018 at 10:25
  • Are you sure your file path is correct.??. Just check it out – Sakkeer A Commented Jun 11, 2018 at 10:28
  • I have deliberately given a wrong url. It is just as an example. – user7889681 Commented Jun 11, 2018 at 10:29
  • Put your file in your assets.And give your file path in href. And try to get download. Then <a href="./assets/examplefile.xlxs" >Download</a> – Sakkeer A Commented Jun 11, 2018 at 10:35
  • As I said, the file is not local. In fact, I won't even have the file. All I get is the file url, not the actual file. – user7889681 Commented Jun 11, 2018 at 10:37
Add a ment  | 

5 Answers 5

Reset to default 1

Just link to it.

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

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 patible 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://....".

use window.open(fileUrl) - will download ;

Do like this,

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

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

本文标签: javascriptDownload file on clicking urlStack Overflow