【问题标题】:How To upload Image using reactjs如何使用 reactjs 上传图片
【发布时间】:2020-11-13 02:46:45
【问题描述】:
我想要实现的是当用户按下choosefile并选择一个图像文件时,js会将图像文件保存在目录中并使用它。
提前致谢 :)
这是我的 HTML:
<Upload onChange={this.onChangeUrl}> <Button> <UploadOutlined /> Click to Upload </Button> </Upload> <Button onClick={this.onSubmit}> Add Card</Button>
这是我得到的错误:
xhr.js:178 POST http://localhost:3000/add 404(未找到)
createError.js:16 Uncaught (in promise) 错误:请求失败
状态码 404
在 createError (createError.js:16)
定居时 (settle.js:17)
在 XMLHttpRequest.handleLoad (xhr.js:61)
是否有我应该实施的发布请求?
【问题讨论】:
标签:
javascript
html
reactjs
antd
【解决方案1】:
安装 Axios:
运行以下命令。
npm install axios --save
示例:
import axios from 'axios';
import React,{Component} from 'react';
class App extends Component {
state = {
// Initially, no file is selected
selectedFile: null
};
// On file select (from the pop up)
onFileChange = event => {
// Update the state
this.setState({ selectedFile: event.target.files[0] });
};
// On file upload (click the upload button)
onFileUpload = () => {
// Create an object of formData
const formData = new FormData();
// Update the formData object
formData.append(
"myFile",
this.state.selectedFile,
this.state.selectedFile.name
);
// Details of the uploaded file
console.log(this.state.selectedFile);
// Request made to the backend api
// Send formData object
axios.post("api/uploadfile", formData);
};
// File content to be displayed after
// file upload is complete
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>
GeeksforGeeks
</h1>
<h3>
File Upload using React!
</h3>
<div>
<input type="file" onChange={this.onFileChange} />
<button onClick={this.onFileUpload}>
Upload!
</button>
</div>
{this.fileData()}
</div>
);
}
}
export default App;
【解决方案2】:
HTML
<form onSubmit={this.onFormSubmit}>
<h3>Upload Profile Picture</h3>
<input type="file" name="userPhoto" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
JS
import { uploadPicture } from "./Actions";
onChange(e) {
this.setState({ file: e.target.files[0] });
}
onFormSubmit(e) {
e.preventDefault();
const formData = new FormData();
formData.append("usrPhoto", this.state.file);
uploadPicture(formData)
.then((res) => {
console.log(res);
});
}
Action.JS
export const uploadPicture = (formData) {
const config = {
headers: {
"content-type": "multipart/form-data",
},
};
return axios
.post([YOUR APP URL] + "api/user/updatePicture", formData, config)
.then(function (response) {
console.log(response.data)
})
.catch(function (error) {
// some error occurred
return [];
});
};
在this.state.file 中,您在服务器上有图像数据命中请求以保存在目录中。