我正在使用带有REACT / AXIOS的cloudinary api,并且想知道如何在axios调用之前以及之后提取数据。我遇到的问题是,如果我使用一个回调,我只能输入一个或另一个数据。所以可以使用两个回调,如果是这样,你会怎么做?
或者我应该以不同的方式解决这个问题?
我想要的是拉出上传的进程并能够将该值存储到州。我唯一的问题是我不确定这样做的正确方法?我需要在onUploadProgress
功能内完成。
以下是代码:
组件中的功能:
uploadImage(files) {
const image = files[0];
const cloudName = 'hyszj0vmt';
const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;
const apiSecret = '***********';
const uploadPreset = '**************';
const timestamp = Date.now() / 1000;
const paramStr = `timestamp=${timestamp}&upload_preset=${uploadPreset}${apiSecret}`;
const signature = sha1(paramStr);
const params = {
api_key: '*******',
timestamp: timestamp,
upload_preset: uploadPreset,
signature: signature
};
APIManager.upload(url, image, params, (err, response) => {
if (err) {
console.log(`UPLOAD ERROR: ${err}`);
return;
}
const imageUrl = response['secure_url'];
let updatedProfile = Object.assign({}, this.state.updated);
updatedProfile['image'] = imageUrl;
this.setState({
updated: updatedProfile
});
});
}
APIManager功能:
upload: (endpoint, file, params, callback) => {
let fd = new FormData();
fd.append('file', file);
Object.keys(params).forEach(key => {
fd.append(key, params[key]);
});
const config = {
headers: { 'X-Requested-With': 'XMLHttpRequest' },
onUploadProgress: progressEvent => {
const progress = Math.round(
progressEvent.loaded * 100.0 / progressEvent.total
);
console.log(progress + '%');
}
};
axios
.post(endpoint, fd, config)
.then(response => {
const { data } = response;
callback(null, data);
})
.catch(err => {
callback(err, null);
});
}
};
答案 0 :(得分:0)
这个怎么样?
upload: (endpoint, file, params, callback, callbackProgress) => {
...
const config = {
headers: { 'X-Requested-With': 'XMLHttpRequest' },
onUploadProgress: progressEvent => {
const progress = Math.round(
progressEvent.loaded * 100.0 / progressEvent.total
);
callbackProgress(progress);
}
};
...
});
用法:
APIManager.upload(url, image, params, (err, response) => {
...
}, (progress) => {
console.log(progress);
});