如何使用formdata React native将Base64数据上传到服务器



我有一个Base64格式的图像。我想使用formdata将其发送到API。如何做到这一点?我使用React原生签名画布来获取签名的Base64。

let signature = base64signature;
const formdata = new FormData();
formdata.append('attachments', {
uri: signature,
name: 'logo',
filename: 'logo',
type: 'image/png',
});

我也关注了这个链接,但不知道如何将其作为表单数据发送到API。它不断出现网络错误。

我也尝试过将其转换为blob并发送,但也没有成功。有人能帮我吗?

var imgBase64 = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCA..." //your bse64 image
onSubmit(){
const file = DataURIToBlob(imgBase64)
const formData = new FormData();
formData.append('upload', file, 'image.jpg') 
formData.append('profile_id', this.profile_id) //other param
formData.append('path', 'temp/') //other param
}
function DataURIToBlob(dataURI: string) {
const splitDataURI = dataURI.split(',')
const byteString = splitDataURI[0].indexOf('base64') >= 0 ? atob(splitDataURI[1]) : decodeURI(splitDataURI[1])
const mimeString = splitDataURI[0].split(':')[1].split(';')[0]
const ia = new Uint8Array(byteString.length)
for (let i = 0; i < byteString.length; i++)
ia[i] = byteString.charCodeAt(i)
return new Blob([ia], { type: mimeString })
}
  1. 您需要安装react-native-fs
import RNFS from 'react-native-fs';
import {Platform} from 'react-native';
const createTempImage = async base64String => {
try {
let base64 = base64String.replace('data:image/png;base64,', '');
const fileName = `${Date.now()}.png`;

const path = `${RNFS.TemporaryDirectoryPath}/${fileName}`;
await RNFS.writeFile(path, base64, 'base64');

const image = {
uri: Platform.OS == 'ios'? path: 'file://' + path,
name: fileName,
type: 'image/png',
};
return image
} catch (error) {
console.log(error);
}
};

没有外部库的最简单方法。

let signature = base64signature;
const formdata = new FormData();
formdata.append('attachments', {
uri: signature, // base64
name: 'logo.png',
type: 'image/png',
});
await axios.post('/', formdata, {headers: {'Content-Type': 'multipart/form-data'}})

最新更新