这是邮递员寄来的
在本机反应中,我如何转换图像并将其作为二进制文件上传到服务器
这是我的代码,我尝试使用标题中插入的表单数据,但仍然无法正常工作 上传成功,但图像未显示
ImagePicker.showImagePicker(options, async (response) => {
if (response.didCancel) {
setIsLoading(false);
} else if (response.error) {
setIsLoading(false);
} else if (response.customButton) {
} else {
setIsLoading(true);
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type: mime});
}
var file = dataURLtoFile(
'data:image/png;base64,' + response.data,
'hello2.png',
);
var myHeaders = new Headers();
myHeaders.append('type', '1');
myHeaders.append('uploadPath', 'xxx');
myHeaders.append('Content-Type', 'image/png');
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: file,
processData: false,
contentType: false,
};
fetch(
'xxx',
requestOptions,
)
.then((response) => response.json())
.then((result) => {
我上传图片后,这就是它的显示方式
我不知道为什么您将文件转换为 data:String,并尝试以 image/png 内容类型上传。您想要 data:string 还是文件本身?如果您想使用 data:String 那么您的内容类型应该是纯文本/文本。
这是我通常上传图片的方法。
const uploadImage = async (response) => {
const put = await fetch(url, { method: 'post', body: response, headers: { "Content-type": response.type } });
}
其中
response
是 ImagePicker.showImagePicker
返回的响应
根据您的服务器,您可能需要表单数据,然后您需要使用 formData 方式。
const uploadImage = async (response) => {
let formData = new FormData();
formData.append('file', response);
//in most case you do not need to create custom header object.
const put = await fetch(url, { method: 'post', body: formData });
}
斑点方法。
const uploadImage = async (response) => {
var blob = new Blob(response);
//in most case you do not need to create custom header object.
const put = await fetch(url, { method: 'post', body: blob, header: { 'Content-type": response.type });
}
上面的示例基于选定的单个文件,如果您选择多个文件,那么响应当然将是一个数组。
我也有同样的问题。
我使用了这个功能并且非常适合我:
const uploadFile = async (file: AttachmentRollObject) => {
let path = file.uri
if (isIphone) {
path = file.uri.replace('file:', '')
} else {
path = file.uri
}
readFile(path, 'base64')
.then(contents => {
const body = Buffer.from(contents, 'base64')
uploadAttachment({
contentType: file.type || '',
contentDisposition: `attachment; filename="${file.name}"`,
body
})
})
.catch((error) => console.log({ error }))}