问题描述
大家好,希望一切顺利
我有一个问题我正在通过 ReactJs 在 Cloudinary 中上传多张图片
这是输入字段
<input
type="file"
className="form-control"
required
onChange={(e) => setimages(e.target.files)}
multiple
/>
OnChange 我将所有文件存储在下面给出的状态
const [images,setimages] = useState([]);
现在我循环状态和上传每个文件到Cloudinary和提取每个图像的URL代码如下
for (const file of images) {
async function upload() {
const formData = new FormData();
formData.append("file",file);
formData.append("upload_preset","DummyPreset"); // Replace the preset name with your own
formData.append("api_key","0300545648961"); // Replace API key with your own Cloudinary key
// Make an AJAX upload request using Axios (replace Cloudinary URL below with your own)
await axios
.post(
"https://api.cloudinary.com/v1_1/Dummycloud/image/upload",formData,{
headers: { "X-Requested-With": "XMLHttpRequest" },}
)
.then((response) => {
const data = response.data;
const fileURL = data.secure_url; // You should store this URL for future references in your app
console.log(fileURL);
});
}
upload();
}
在这里我可以将每个链接提取为 fileURL 并对其进行安慰
console.log(fileURL);
要查看输出请点击链接,它会将您重定向到图像 Outputimage
正如你所看到的,现在所有的 URL 都被提取了,我想将所有提取的 URL 推送到一个数组中,并希望将它们发送到 Express Server,在那里我将它们存储到 DB 中
请让我知道如何将所有 URL 存储到状态数组中,每当提取出的任何 URL 都将存储到该数组中
解决方法
// this function returns a Promise
const uploadFile = (file) => {
const formData = new FormData();
formData.append(stuff);
return axios.post('some/path',formData).then(response => response.data.secure_url);
};
Promise.all(images.map(uploadFile)).then(fileURLs => storeFileURLs(fileURLs))
,
解决办法
感谢您的贡献
var ImagesUrlArray = [];
for (const file of image) {
async function upload() {
const formData = new FormData();
formData.append("file",file);
formData.append("upload_preset","DummyPreset"); // Replace the preset name with your own
formData.append("api_key","0300545648961"); // Replace API key with your own Cloudinary key
// Make an AJAX upload request using Axios (replace Cloudinary URL below with your own)
await axios
.post(
"https://api.cloudinary.com/v1_1/Dummycloud/image/upload",formData,{
headers: { "X-Requested-With": "XMLHttpRequest" },}
).then((response) => {
const data = response.data;
var fileURL = data.secure_url; // You should store this URL for future references in your app
ImagesUrlArray = [...ImagesUrlArray];
ImagesUrlArray.push(fileURL);
if (ImagesUrlArray.length === image.length) {
const res = axios
.post("http://localhost:5000/register",{
fullname: Data.fullname,email: Data.email,pass: Data.pass,cpass: Data.cpass,phone: Data.phone,imagee: ImagesUrlArray,})
.then((response) => response);
setdataa(res);
}
});
}
upload();
}