javascript - 我的文件(pdf、xlsx、docx ..)在 Reactjs 中下载损坏或有错误

标签 javascript reactjs rest blob

我正在使用 React Js 和 Axios 向 API 发出请求。 我正在尝试使用 ReactJs 通过 API 下载文件,但是当他们下载并尝试打开时,我收到一条错误消息:“文件已损坏或已损坏”。

文件通过GET请求获取,类型可以是pdf、xlxs、docx等),mime通过父组件的props获取

这是我的代码(我的组件的一部分)

fetchFile(){

  axios
    .get(`/someurl/thefiles/${this.props.file.id}`, { headers })

    .then(response => {
    
          let url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download",
          `${this.props.file.name}.${this.props.file.mime}`);
          document.body.appendChild(link);
          link.click();
  });


}

render(){

  return(
      
      <button onClick={this.fetchFile}> Download file </button>
    
  )

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>

mime 和文件名来自父组件。

我遇到的问题是我下载了一个文件,例如 xlsx,当我打开它时,我收到一个错误框,其中显示消息“文件已损坏”,如果我下载一个 pdf 文件,它可以毫无问题地下载,并且当我打开 pdf 时,它是完全空白的:与原始页数相同,但都是白色的。

我在 chrome、firefox 和 brave 上尝试,错误是一样的

最佳答案

这个答案来自@hexebioc

fetchFile(){
   axios({
            url: `/someurl/thefiles/${this.props.file.id}`,
            method: "GET",
            headers: headers,
            responseType: "blob" // important
        }).then(response => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute(
                "download",
                `${this.props.file.name}.${this.props.file.mime}`
            );
            document.body.appendChild(link);
            link.click();
        });


}

render(){

  return(
      
      <button onClick={this.fetchFile}> Download file </button>
    
  )

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

关于javascript - 我的文件(pdf、xlsx、docx ..)在 Reactjs 中下载损坏或有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64251654/

相关文章:

javascript - jQuery Ajax 调用在有效 URL 上失败

javascript - next.js 动态导入时出现 ESLint React/display-name 错误

javascript - Angularjs:如何编写 $http 作为 Controller 的 promise

javascript - 调用一个函数,在每次状态更改时触发服务调用

javascript - 为什么即使在 Prop 对象更改后功能组件也不会重新渲染?

javascript - 在 react 中获取总是返回(JSON 中位置 0 处的意外标记 R)

jquery - 使用 jquery ajax 捕获 401 未经授权的 http 响应

javascript - PHP 发布的值之一不正确

javascript - 如何在cordova中的sqlite事务中传递参数

php - 使用 RESTful API 调用注册用户