【发布时间】:2021-09-01 06:12:25
【问题描述】:
我正在尝试使用 react 和 node 从客户端中的服务器下载文件。这是我用来在前端实现下载btn的代码:
import React from "react";
import { Button } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
class DownloadBtn extends React.Component {
constructor(props) {
super(props);
this.state ={
fileDownloadUrl: ""
}
}
dofileDownload(){
console.log(this.state.fileDownloadUrl);
}
handleFile (response){
console.log(response);
const blob = new Blob([response]); // Step 3
const fileDownloadUrl = URL.createObjectURL(blob); // Step 4
this.setState ({fileDownloadUrl: response.url},//fileDownloadUrl}, // Step 5
() => {
this.dofileDownload.click(); // Step 6
URL.revokeObjectURL(fileDownloadUrl); // Step 7
this.setState({fileDownloadUrl: ""})
})
}
handleClick (){
fetch(this.props.fileName, {
method: 'GET',
'content-type': 'application/octet-stream',
})
.then((response) => this.handleFile(response));
}
render() {
return (
<div>
<Button onClick={() => this.handleClick()} variant="outline-primary">Download</Button>
<a
download={this.props.fileName}
href={this.state.fileDownloadUrl}
ref={e=>this.dofileDownload = e}
>download</a>
</div>
);
}
}
export default DownloadBtn;
服务器正在工作。当我检查时
GET http://localhost:3000/gcode/lucas/1623843541661.gcode
request 我可以在响应的正文中看到该文件。但是当我console.log(response) 我得到:
Response {type: "basic",
url: "http://localhost:3000/gcode/lucas/1623843541661.gcode",
redirected: false,
status: 200,
ok: true,
body: ReadableStream,
bodyUsed: false,
…}
下载文件的内容:
[object Response]
谁能告诉我哪里错了?为什么即使请求成功,它也没有下载正确的文件?还有其他更简单的方法可以从服务器下载文件吗?
【问题讨论】:
标签: javascript reactjs blob downloadfile