我正在使用ReactJS,并上传图片。为此,我使用了Ant Design(版本4.6)的upload组件。在某些情况下,我的上传失败,对于这些情况,我想添加一个重试功能,它将再次上传图片,而不必再次选择它,但我找不到方法来做到这一点。任何帮助都将不胜感激。谢谢!
这是我使用upload组件的代码块:
<Form.Item name="my_photos" colon={false}>
{getFieldDecorator("my_photos", {
valuePropName: "my_photos",
getValueFromEvent: e => e && e.fileList,
rules: [{ required: false, message: 'Upload at least two photos' }],
})(
<div className="d-flex">
<Upload {...Constants.props}
multiple={true}
listType="text"
className="uploadbtn"
progress= {{
strokeColor: {
'0%': '#108ee9',
' 100%': '#87d068',
},
strokeWidth: 3,
format: percent => `${parseFloat(percent.toFixed(2))}%`,
}}>
<div>Browse</div>
</Upload>
</div>
)}
</Form.Item>这是我的项目中另一个命名为常量的常量,它包含了我的自定义上传请求:
export const props = {
customRequest({
action,
data,
file,
filename,
headers,
onError,
onProgress,
onSuccess,
withCredentials
}) {
var jwt_token = localStorage.getItem(<Token_Name>);
AWS.config.update({
region: <Region Name>,
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: <PoolID>,
Logins: {
<Login>: jwt_token,
}
})
});
const S3Obj = new AWS.S3();
const objectParameters = {
Bucket: "my_bucket",
Key: "my_bucket_files" + "/" + file.uid + "/" + file.name,
ACL: 'public-read',
Body: file,
ContentType: file.type
};
S3Obj.putObject(objectParameters)
.on("httpUploadProgress", function({ loaded, total }) {
onProgress(
{
percent: Math.round((loaded / total) * 100)
},
file
);
})
.send(function(err, data) {
if (err) {
onError();
message.error('Upload Failed. Try Again.');
console.log(err.code);
console.log(err.message);
} else {
onSuccess(data.response, file);
message.success('Upload Successful!');
}
});
}
};发布于 2020-10-07 05:37:55
只需添加另一个按钮来处理重试,并在代码更改时查看它。
请参阅https://codesandbox.io/s/epic-dawn-pbktg?file=/index.js
在代码中:
您需要添加的内容:
代码:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Upload, message, Button } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import reqwest from "reqwest";
function App() {
const [fileList, setFileList] = useState([]);
const [hasError, setHasError] = useState(false);
const [uploading, setUploading] = useState(false);
const props = {
name: "file",
action: "https://www.mocky.io/v2/5cc8019d300000980a055e76",
headers: {
authorization: "authorization-text"
},
onChange(info) {
if (info.file.status !== "uploading") {
console.log(info.file, info.fileList);
}
if (info.file.status === "done") {
message.success(`${info.file.name} file uploaded successfully`);
setHasError(false);
setFileList([]);
} else if (info.file.status === "error") {
message.error(`${info.file.name} file upload failed.`);
setHasError(true);
setFileList([...fileList, info.file]);
}
}
};
const handleRetry = () => {
const formData = new FormData();
const files = fileList.filter((file) => file.status === "error");
files.forEach((file) => {
formData.append("files[]", file);
});
setUploading(true);
// You can use any AJAX library you like
reqwest({
url: "https://www.mocky.io/v2/5cc8019d300000980a055e76",
method: "post",
processData: false,
data: formData,
success: () => {
setUploading(false);
setHasError(false);
setFileList([]);
message.success("upload successfully.");
},
error: () => {
setUploading(false);
setHasError(true);
setFileList([...fileList]);
message.error("upload failed.");
}
});
};
return (
<>
<Upload {...props}>
<Button icon={<UploadOutlined />}>Click to Upload</Button>
</Upload>
{hasError && (
<Button
type="primary"
onClick={handleRetry}
disabled={fileList.length === 0}
loading={uploading}
style={{ marginTop: 16 }}
>
{uploading ? "Uploading" : "Retry"}
</Button>
)}
</>
);
}
ReactDOM.render(<App />, document.getElementById("container"));<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container"></div>
https://stackoverflow.com/questions/64233479
复制相似问题