使用axios和react native上传base64图片到服务器
Upload base64 image to the server with Axios and React native
实际上我们有网站使用 dropzone.js 将图片上传到服务器。
我正在使用 React 本机应用程序,需要复制 dropzone js 行为。
我正在尝试发送 base64 图像,但请求 return Multipart requests must contain at least one part.
saveImages(images) {
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'X-Requested-With': 'XMLHttpRequest'
}
};
images.forEach(img => {
let imgFormData = `data:${img.mime};base64,${(img.data)}`;
let blob = this.dataURItoBlob(imgFormData);
let formData = new FormData(document.forms[0]);
formData.append('file', blob);
axios.post(SAVE_IMAGE_URL, formData, config)
.then(res => console.log(res))
.catch(err => {
console.log(err);
console.log(err.status);
console.log(err.code);
})
});
}
dataURItoBlob = (dataURI) => {
let byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
let ia = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
修复了 react-native-fetch-blob 包
images.forEach(img => {
RNFetchBlob.fetch('POST', SAVE_IMAGE_URL, {
'Content-Type': 'multipart/form-data'
}, [
// element with property `filename` will be transformed into `file` in form data
{name: 'file', filename: 'file.png', data: img.data}
]).then((resp) => {
console.log(resp);
// ...
}).catch((err) => {
// ...
})
})
实际上我们有网站使用 dropzone.js 将图片上传到服务器。
我正在使用 React 本机应用程序,需要复制 dropzone js 行为。
我正在尝试发送 base64 图像,但请求 return Multipart requests must contain at least one part.
saveImages(images) {
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'X-Requested-With': 'XMLHttpRequest'
}
};
images.forEach(img => {
let imgFormData = `data:${img.mime};base64,${(img.data)}`;
let blob = this.dataURItoBlob(imgFormData);
let formData = new FormData(document.forms[0]);
formData.append('file', blob);
axios.post(SAVE_IMAGE_URL, formData, config)
.then(res => console.log(res))
.catch(err => {
console.log(err);
console.log(err.status);
console.log(err.code);
})
});
}
dataURItoBlob = (dataURI) => {
let byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
let ia = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
修复了 react-native-fetch-blob 包
images.forEach(img => {
RNFetchBlob.fetch('POST', SAVE_IMAGE_URL, {
'Content-Type': 'multipart/form-data'
}, [
// element with property `filename` will be transformed into `file` in form data
{name: 'file', filename: 'file.png', data: img.data}
]).then((resp) => {
console.log(resp);
// ...
}).catch((err) => {
// ...
})
})