React-每个文件的上传进度



Im running into a problem related with file uploading. Im基于react Dropzone库制作Dropzone组件。我需要上传文件,并显示每个文件的上传进度。此外,我想保持我上传的文件(结果(在区域和删除只有用户点击。

这是我的报税表。

return (
<Container {...getRootProps({ isDragActive, isDragAccept, isDragReject })}>
<input {...getInputProps()} />
{filesToRender || (
<p>Drag 'n' drop some files here, or click to select files</p>
)}
</Container>
);

在我把一些文件拖进区域后,它调用这个函数:

const onDrop =  acceptedFiles => {
for (const file of acceptedFiles) {
const formData = new FormData();
formData.append("file", file);
axios.post(`http://localhost:8080/files`, formData, {
headers: {
Authorization:
"Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmb28iLCJleHAiOjE1ODIxNzc2NjAsImlhdCI6MTU4MjE0MTY2MH0.CWtDOIrFoitXHDeXCha0mT3HVyvTrwg8nXhsNaLkZVs"
},
onUploadProgress: progressEvent => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
file.progress = percentCompleted;
// set progress for an each file
}
});
}
setFiles([...files, ...acceptedFiles]);
};

我想设置文件,然后在上传过程中以某种方式更改它

我的文件要渲染:

const filesToRender =
files.length &&
files.map((file, index) => {
return (
<File key={index}>
<FileInfo>
{file.name}
{file.progress} //get progress from an each file object
</FileInfo>
<Button onClick={event => removeFile(event, index)}>
Убрать файл
</Button>
</File>
);
});

我该怎么做?setFiles是异步的,所以我在重新设置它时遇到了问题。

您需要在进度更新后更新状态:

const onDrop = (acceptedFiles) => {
acceptedFiles.map((file, index) => {
const formData = new FormData();
formData.append("file", file);
axios.post(`http://localhost:8080/files`, formData, {
headers: {
Authorization:
"Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmb28iLCJleHAiOjE1ODIxNzc2NjAsImlhdCI6MTU4MjE0MTY2MH0.CWtDOIrFoitXHDeXCha0mT3HVyvTrwg8nXhsNaLkZVs",
},
onUploadProgress: (progressEvent) => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
file.progress = percentCompleted;
// set progress for an each file
setFiles((prevFiles) => {
if (prevFiles[index]) {
prevFiles[index] = file;
}
return [...prevFiles];
});             
},
});
});
setFiles([...files, ...acceptedFiles]);
};

相关内容

  • 没有找到相关文章

最新更新