【发布时间】:2019-07-25 11:13:38
【问题描述】:
您好,我正在使用以下代码在 Cloudinary 上传图片
import React, { Component } from 'react';
import './App.css';
import Dropzone from 'react-dropzone';
import axios from 'axios';
const FETCH_URL = `https://res.cloudinary.com/${USER_NAME}/image/fetch`;
const options = 'w_300';
export const getUrl = (url, options = '') => {
return `${FETCH_URL}/${options}${encodeURIComponent(url)}`;
};
class App extends Component {
state = {
image: null,
upload: null,
number: '',
};
handleDrop = (files) => {
// Push all the axios request promise into a single array
this.setState({ number: files.length });
const uploaders = files.map(file => {
// Initial FormData
const formData = new FormData();
formData.append('file', file);
formData.append('tags', 'codeinfuse, medium, gist');
formData.append('upload_preset', 'fake'); // Replace the preset name with your own
formData.append('api_key', '444445'); // Replace API key with your own Cloudinary key
formData.append('timestamp', (Date.now() / 1000) | 0);
// Make an AJAX upload request using Axios (replace Cloudinary URL below with your own)
return axios.post('https://api.cloudinary.com/v1_1/what/upload', formData, {
headers: { 'X-Requested-With': 'XMLHttpRequest' },
}).then(({ data }) => {
const fileURL = data.secure_url; // You should store this URL for future references in your app
this.setState({ upload: fileURL });
});
});
// Once all the files are uploaded
axios.all(uploaders)
.then(() => {
return getUrl(this.state.upload, options);
})
.then(photo => this.setState({ image: photo }));
}
render() {
console.log(this.state.upload)
return (
<div className="App">
<Dropzone
onDrop={this.handleDrop}
multiple
accept="image/*"
>
<p>Drop your files or click here to upload</p>
</Dropzone>
<br />
{this.state.upload}
</div>
);
}
}
export default App;
我已在 dropzone 启用多个文件上传。在 cloudinary 上传文件也可以。但问题是当我上传多个文件时,它会生成多个响应并且值会发生变化。如您所见,我将对状态的响应保存为this.state.upload。如何在不丢失任何价值的情况下存储所有响应。谢谢
【问题讨论】:
-
引入一个数组来保存每次上传的状态。
标签: javascript reactjs axios dropzone.js