如何使用 fetch 在 react-native-image-crop-picker 中使用 react native 上传二进制文件
How to use fetch to upload binary file in react native with react-native-image-crop-picker
我在上传文件到服务器时遇到了一些问题,因为我找不到将 img 转换为二进制数据结构的方法。
像这样大摇大摆的成功请求
// upload function
const UploadImg = async (img: any) => {
// img from react-native-image-crop-picker
const fromData = new FormData();
fromData.append('file', `${img.data}`);
return fetch(`${API_URL_R}/upload`, {
method: 'POST',
body: fromData, // this should be binary
})
};
// use
// import ImagePicker from 'react-native-image-crop-picker'
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true,
includeBase64: true,
}).then(async image => {
await UploadImg(image);
});
从 ImagePicker.openPicker 中收到的图片,您将收到 image.path、image.filename 和 image.mime,然后您可以按以下方式上传图片
注意:文件名也可以接收为
让文件名 = path.substring(path.lastIndexOf('/') + 1, path.length)
上传图片
const UploadImg = async () => {
const fromData = new FormData();
fromData.append("file", {
name: filename,
type: mime,
uri:
Platform.OS === "android"
? filepath
: filepath.replace("file://", "")
});
var url = uploadImageUrl
const response = await fetch(url, {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data",
Accept: "application/json",
Authorization: authToken
},
body: fromData,
})
}
我在上传文件到服务器时遇到了一些问题,因为我找不到将 img 转换为二进制数据结构的方法。
像这样大摇大摆的成功请求
// upload function
const UploadImg = async (img: any) => {
// img from react-native-image-crop-picker
const fromData = new FormData();
fromData.append('file', `${img.data}`);
return fetch(`${API_URL_R}/upload`, {
method: 'POST',
body: fromData, // this should be binary
})
};
// use
// import ImagePicker from 'react-native-image-crop-picker'
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true,
includeBase64: true,
}).then(async image => {
await UploadImg(image);
});
从 ImagePicker.openPicker 中收到的图片,您将收到 image.path、image.filename 和 image.mime,然后您可以按以下方式上传图片
注意:文件名也可以接收为 让文件名 = path.substring(path.lastIndexOf('/') + 1, path.length)
上传图片
const UploadImg = async () => {
const fromData = new FormData();
fromData.append("file", {
name: filename,
type: mime,
uri:
Platform.OS === "android"
? filepath
: filepath.replace("file://", "")
});
var url = uploadImageUrl
const response = await fetch(url, {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data",
Accept: "application/json",
Authorization: authToken
},
body: fromData,
})
}