I am trying to download a file from my server in the client using react and node. This is the code I am using to implement the download btn in the front-end:
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;
The server is working. When I inspect
GET http://localhost:3000/gcode/lucas/1623843541661.gcode
request I can see the file in the body of the response. But when I console.log(response)
I get:
Response {type: "basic",
url: "http://localhost:3000/gcode/lucas/1623843541661.gcode",
redirected: false,
status: 200,
OK: true,
body: ReadableStream,
bodyUsed: false,
…}
The content of the downloaded file:
[object Response]
Can anybody tell what is wrong? Why isn't it downloading the right file even though the request is successful? Is there any other easier way to download a file from the server?
You should use the blob
method provided by the response object (Doc).
Replace the handleFile
method with:
handleFile(response) {
console.log(response);
response.blob().then((blob) => {
const fileDownloadUrl = URL.createObjectURL(blob);
this.setState({ fileDownloadUrl: response.url }, () => {
this.dofileDownload.click();
URL.revokeObjectURL(fileDownloadUrl);
this.setState({ fileDownloadUrl: "" })
});
});
}
The Blob
constructor accepts an array containing the file content (Doc). Any value which is not the expected type will be converted to string. The default string representation of a response object is [object Response]
.