来源:未知 时间:2023-09-14 14:43 作者:小飞侠 阅读:次
[导读] 以下是一个基本的React表单上传示例,它使用axios库来将文件上传到服务器: importReact,{useState}fromreact;importaxiosfromaxios;functionFileUploadForm(){const[file,setFile]=useState(null);const[uploadPercentage,set...
|
以下是一个基本的React表单上传示例,它使用axios库来将文件上传到服务器: import React, { useState } from "react";
import axios from "axios";
function FileUploadForm() {
const [file, setFile] = useState(null);
const [uploadPercentage, setUploadPercentage] = useState(0);
const fileSelectedHandler = event => {
setFile(event.target.files[0]);
};
const fileUploadHandler = () => {
const formData = new FormData();
formData.append("file", file);
axios
.post("/upload", formData, {
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(response => {
console.log("File uploaded successfully");
})
.catch(error => {
console.error("Failed to upload file", error);
});
};
const uploadPercentageHandler = () => {
if (file) {
let reader = new FileReader();
reader.onload = function(e) {
setUploadPercentage(e.loaded / e.total * 100);
};
reader.readAsDataURL(file);
}
};
return (
<div>
<input type="file" onChange={fileSelectedHandler} />
<button onClick={fileUploadHandler}>Upload</button>
<button onClick={uploadPercentageHandler}>Show Progress</button>
<p>{uploadPercentage}%</p>
</div>
);
}
export default FileUploadForm;这个示例包含一个文件输入框、一个上传按钮和一个进度条。当用户选择文件后,文件会存储在file状态变量中。当用户点击上传按钮时, 会将文件作为multipart/form-data格式的请求体发送到服务器。服务器响应后, 上传完成。此外,还有一个按钮可以显示上传进度,通过FileReader读取文件进度条实现。 |
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com