极简写法,只需要两个元素就足够,一个 input, 一个 button。 input 需要设置 type = "file" , 然后添加一个 onChange listener, 用户选择任何文件,selectedFile 将被设为新选择的文件,点击 “Upload to Server” 上传selectedFile 到后端。 代码如下:
import React, { useState } from "react";
import "./App.css";
function App() {
const [selectedFile, setSelectedFile] = useState(null);
const selecteFileHandler = (event) => {
setSelectedFile(event.target.files[0]);
};
const uploadHandler = () => {
console.log("The file to be sent is:", selectedFile.name);
const formData = new FormData();
formData.append('image', selectedFile);
axios.post("some backend end api point.....", formData)
.then(res => {
console.log(res)
})
};
return (
<div className="App">
<input type="file" onChange={selecteFileHandler} />
<button onClick={uploadHandler}>Upload to Server</button>
</div>
);
}
export default App;
复杂一点的写法:主要是因为上面的 input 元素默认样式比较 ugly ,一般将其隐藏,新增一个 button ,然后,每次点击这个 button ,被隐藏的 input 执行其原来的功能。 代码:
import React, { useRef, useState } from "react";
import "./App.css";
function App() {
const [selectedFile, setSelectedFile] = useState(null);
const hiddenFileInputRef = useRef(null);
const selecteFileHandler = (event) => {
setSelectedFile(event.target.files[0]);
};
const uploadHandler = () => {
console.log("The file to be sent is:", selectedFile.name);
const formData = new FormData();
formData.append("image", selectedFile, selectedFile.name);
axios
.post("some backend end point.....", formData, {
onUploadProgress: (progressEvent) => {
console.log(
"Upload Progress: " +
Math.round((ProgressEvent.loaded / progressEvent.total) * 100) +
"%"
);
},
})
.then((res) => {
console.log(res);
});
};
const pickImageHandler = () => {
hiddenFileInputRef.current.click();
};
return (
<div className="App">
<input
style={{ display: "none" }}
type="file"
onChange={selecteFileHandler}
ref={hiddenFileInputRef}
/>
<button onClick={pickImageHandler}>Pick a Image</button>
<button onClick={uploadHandler}>Upload to Server</button>
</div>
);
}
export default App;
参考网页:
- 油鹳,
- https://medium.com/web-dev-survey-from-kyoto/how-to-customize-the-file-upload-button-in-react-b3866a5973d8
- https://www.pluralsight.com/guides/how-to-use-a-simple-form-submit-with-files-in-react
- https://www.geeksforgeeks.org/file-uploading-in-react-js/
|