【发布时间】:2020-11-25 12:44:13
【问题描述】:
我希望 react js 中的进度条在将数据插入数据库时并行更新。我一直使用的后端是spring boot,我想更新进度条,直到我的控制器从服务器的端点发送状态200。
我的要求是在数据库中插入一个对象数组,比如100多个对象,同时,必须更新进度条,直到所有对象都插入数据库。
这是我的客户端代码
class UploadMultiPleFiles extends React.Component{
constructor()
{
super();
this.state={
fileArr:[],
progress:0,
}
}
changeFile=(event)=>{
const filedata=event.target.files;
var arr=[];
if(filedata.length!==0)
{
for(let i=0;i<filedata.length;i++)
{
var obj={}
obj.name=filedata[i].name;
obj.type=filedata[i].type;
arr.push(obj);
}
}
this.setState({
fileArr:arr
})
console.log(obj);
console.log(this.state.fileArr)
}
upload=()=>
{
let currentFile=this.state.selectedFiles[0];
this.setState({
progress:0,
currentFile:currentFile,
});
let formData=new FormData();
formData.append("file",currentFile);
}
onFileSubmit=(e)=>{
e.preventDefault();
axios({method:'post',
data: this.state.fileArr,
url:'http://localhost:8080/postList',
onUploadProgress:(ev:ProgressEvent)=>{
const progress=((ev.loaded*100)/ev.total);
this.setState(
{
progress:progress
}
)
console.log(progress)
}
}
).then((res)=>{
console.log(res.status)
})
}
render()
{
return(
<Container>
<h1>Upload Multiple Files</h1>
<Form style={{paddingTop:10}} onSubmit={this.onFileSubmit} className="mt-1">
<Form.Group controlId="formBasicEmail">
<Form.Control type="file" size="lg" name="file" onChange={this.changeFile} multiple/>
</Form.Group>
<Button variant="primary" type="submit">Submit Files</Button>
</Form>
<h4>Files which are uploaded </h4>
<ProgressBar now={this.state.progress}/>
<Table className="mt-1" variant="dark" striped bordered hover size="sm" style={{paddingLeft:100}} >
<thead>
<tr>
<th>File Name</th>
<th>File Type</th>
</tr>
</thead>
<tbody>
{this.state.fileArr.map(c =>
<tr>
<td>{c.name}</td>
<td>{c.type}</td>
</tr>
)}
</tbody>
</Table>
</Container>
);
}
}
spring boot 中的后端代码
@CrossOrigin(origins="http://localhost:3000")
@PostMapping("/postList")
public void pushData(@RequestBody List<FileUpload> fileUploads)
{
opservice.saveAllFiles(fileUploads);
}
}
模型类
@Entity
public class FileUpload {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String type;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
【问题讨论】:
-
在句尾添加问号并不代表它是一个问题。提出一个问题+您尝试过的内容+您遇到的问题。
标签: javascript reactjs spring-boot spring-mvc spring-data-jpa