简体   繁体   English

如何在reactjs中下载来自服务器的任何文件

[英]How to download any file coming from sever in reactjs

I am getting some file path from sever using API, but here I want to download those file if click on them. 我从使用API​​的服务器获取一些文件路径,但是在这里,如果单击它们,我想下载这些文件。 I am using react js-file download package. 我正在使用react js文件下载包。 what I have code so far is below. 我到目前为止的代码如下。

        downloadFileforUser =(path)=>{
         var data = (baseUrl+'/SurveyImages/'+path )
         fileDownload(data, path);

 }

it is downloading file but I can not read those file such pdf, jpg,png, please help me I am new to Reactjs Thanks 它正在下载文件,但我无法读取这些文件,例如pdf,jpg,png,请帮助我,我是Reactjs的新手

This is not related to React. 这与React无关。 However, you can use the download attribute on the anchor element to tell the browser to download the file. 但是,您可以使用锚元素上的download属性来告诉浏览器下载文件。

<a href='your file path' download>Click to download</a>

This is not related to reactjs but it's javascript related so you can take a look at this sample 这与reactjs不相关,但是与javascript有关,因此您可以看一下这个示例

In mozilla docs example: 在mozilla docs示例中:

var myHeaders = new Headers();

var myInit = { method: 'GET',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' };

var myRequest = new Request('flowers.jpg', myInit);

    fetch(myRequest).then(function(response) {
      return response.blob();
    }).then(function(myBlob) {
      var objectURL = URL.createObjectURL(myBlob);
      myImage.src = objectURL;
    });

You can read full code here 您可以在此处阅读完整的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM