如何在本机反应中将图像读取为二进制/ blob
Posted
技术标签:
【中文标题】如何在本机反应中将图像读取为二进制/ blob【英文标题】:How to read image as binary/blob in reactnative 【发布时间】:2020-06-15 03:37:56 【问题描述】:我用react-native-camera
拍照,它会像保存在手机里一样
file:///data/user/0/xxx/cache/Camera/4b1bde90-fa5e-4f91-aac1-029a8b67b3fc.jpg
现在我想将这张图片上传到服务器,我的 API 方案如下
const formData = new FormData();
formData.append('file', file); // should be binary, but I don't know how to read image file as binary to here
formData.append('userId', 1); //
formData.append('userType', 'normal');
在 SO 上搜索后,我资助了一些图书馆 rn-fetch-blob
和 react-native-image-picker
但仍然不知道如何将图像转换为二进制/blob。
【问题讨论】:
你好……你的问题解决了吗? 【参考方案1】:试试这个,它对我有用
const response = await fetch(pathToImageFile)
const blob = await response.blob()
【讨论】:
【参考方案2】:使用 react-native-image-picker 捕获图像
launchCamera(options, (response) =>
console.log('Response = ', response);
if (response.didCancel)
alert('User cancelled camera picker');
return;
else if (response.errorCode == 'camera_unavailable')
alert('Camera not available on device');
return;
else if (response.errorCode == 'permission')
alert('Permission not satisfied');
return;
else if (response.errorCode == 'others')
alert(response.errorMessage);
return;
console.log('base64 -> ', response.base64);
console.log('uri -> ', response.uri);
console.log('width -> ', response.width);
console.log('height -> ', response.height);
console.log('fileSize -> ', response.fileSize);
console.log('type -> ', response.type);
console.log('fileName -> ', response.fileName);
setFilePath(response);
);
上传图片
const data = new FormData();
data.append("uploadFile",
name: filename,
type: type,
uri:
Platform.OS === "android"
? fileuri
: fileuri.replace("file://", "")
);
var url = uploadProfilePic
axios.post(url, data, headers:
"Content-Type": "multipart/form-data",
Accept: "application/json",
Authorization: authToken
)
.then((res) =>
)
.catch((err) =>
)
【讨论】:
以上是关于如何在本机反应中将图像读取为二进制/ blob的主要内容,如果未能解决你的问题,请参考以下文章