嗨,我需要在遗留应用程序中使用class
component
来上传文件到react
。我只需要将这个文件保存在UI
中,所以不想将其保存到数据库中。我需要将其保存在public folder
下,并且还需要让用户能够输入文件和文件夹的名称。
我需要对下面的代码做哪些更改?下面的代码完全正常工作。唯一的问题是我需要将文件上传到文件夹中,并手动输入file and folder name
。
import axios from 'axios';
import React, { Component } from 'react';
class FileUpload extends Component {
state = {
selectedFile: null,
};
onFileChange = (event) => {
this.setState({ selectedFile: event.target.files[0] });
};
onFileUpload = () => {
const formData = new FormData();
formData.append(
'myFile',
this.state.selectedFile,
this.state.selectedFile.name
);
console.log(this.state.selectedFile);
axios.post('api/uploadfile', formData); //I need to change this line
};
fileData = () => {
if (this.state.selectedFile) {
return (
<div>
<h2>File Details:</h2>
<p>File Name: {this.state.selectedFile.name}</p>
<p>File Type: {this.state.selectedFile.type}</p>
<p>
Last Modified:{' '}
{this.state.selectedFile.lastModifiedDate.toDateString()}
</p>
</div>
);
} else {
return (
<div>
<br />
<h4>Choose before Pressing the Upload button</h4>
</div>
);
}
};
render() {
return (
<div>
<h1>Plese select the translation file</h1>
<div>
<input type="file" onChange={this.onFileChange} />
<button onClick={this.onFileUpload}>Upload!</button>
</div>
{this.fileData()}
</div>
);
}
}
export default FileUpload;
编辑1:
编辑2:
app.listen(80, () => console.log('Listening on port 80'));
axios.post('http://localhost:80/api/uploadfile', formData, {
server/index.js
中将端口更改为80
了吗?然后将请求更改为axios.post("http://localhost:80/api/uploadfile"
。 - Amila Senadheerayarn start
并重新运行。当前命令无法使用热重载。 - Amila Senadheera