这是单张图片上传:
const [img, setImg] = useState<File>();
<input type="file" id="file" onChange={fileChange} />
this if upload handler
const handleUpload = async () => {
// ARRAY OF IMAGES
const mediaData = new FormData();
for (var i = 0; i < file.length; i++) {
mediaData.append('media[]', file[i]);
}
// aws-sdk upload for single image
const path = `events/${eventDetails.id}/${img?.name}`;
const target = {
Bucket: process.env.REACT_APP_HOST_AWS_BUCKET,
Key: path,
Body: img,
ContentType: 'image/jpg',
};
const creds = {
accessKeyId: process.env.REACT_APP_HOST_AWS_ACCESS_KEY_ID || '',
secretAccessKey: process.env.REACT_APP_HOST_AWS_SECRET_ACCESS_KEY || '',
};
try {
const parallelUploads3 = new Upload({
client: new S3Client({
region: process.env.REACT_APP_HOST_AWS_DEFAULT_REGION || '',
credentials: creds,
}),
leavePartsOnError: false,
params: target,
});
parallelUploads3.on('httpUploadProgress', (progress) => {
console.log(progress);
});
parallelUploads3.done();
} catch (e) {
console.log(e);
}
这是我所做的单个图像上传,它的工作原理,但我想要的是上传多个文件(数组的图像mediaData上面提到),我如何实现这一点?如果没有任何帮助,我不知道该怎么做。
用于并行上传多张图片并获取上传进度
const handleUploadImage = () => {
for (var i = 0; i < file.length; i++) {
const imgFile = file[i];
const path = `folder/${file[i].name}`;
const target = {
Bucket: process.env.REACT_APP_HOST_AWS_BUCKET,
Key: path,
Body: imgFile,
ContentType: "image/jpeg"
};
const creds = {
accessKeyId: process.env.REACT_APP_HOST_AWS_ACCESS_KEY_ID || "",
secretAccessKey: process.env.REACT_APP_HOST_AWS_SECRET_ACCESS_KEY || ""
};
try {
const parallelUploads3 = new Upload({
client: new S3Client({
region: process.env.REACT_APP_HOST_AWS_DEFAULT_REGION || "",
credentials: creds
}),
leavePartsOnError: true,
partSize: 1024 * 1024 * 1000,
params: target
});
parallelUploads3.on("httpUploadProgress", (progress: any) => {});
await parallelUploads3.done();
} catch (e) {
console.error(e);
}
}
}