我见过几个使用react-native-fetch-blob
上传文件以将资源上传为表单数据的示例,遗憾的是我需要上传到的服务器不支持多部分,而是文件的二进制流。我正在使用react native(dettached)并创建了一个本机模块(iOS),它返回本地标识符和要上载的文件的本地路径,例如:
4697EAE5-50A3-4462-AE5A-71CC5D08C2D7/L0/001: file:///var/mobile/Media/DCIM/100APPLE/IMG_0038.JPG
但是,当我指定要上传的库的路径时,它会上传一个空流,服务器会存储一个零字节大小的文件,我正在上传我正在做的事情的片段:
export const uploadFile = (
action,
url,
data,
showLoading = true,
showError = true
) => (dispatch, getStore) => { // in the future it's going to be connected to redux
const uploadPath = RNFetchBlob.wrap(data.replace("file://", ""));
// uploadPath = "RNFetchBlob-file:///var/mobile/Media/DCIM/100APPLE/IMG_0033.JPG"
console.log("path to upload", uploadPath);
return RNFetchBlob.fetch(
"PUT",
url,
{
// appends the Bearer token of the server
...getConfigFromStore(getStore()).headers
"Content-Type": "application/octet-stream"
},
uploadPath
)
.then(response => console.log("response ok", response))
.catch(error => console.error("response error", error));
};
响应是HTTP 204(由于响应不包含正文,因此很好)
另一种方法是获取base64字符串数据,但由于手机中的内存限制而不建议这样做,我需要支持将来上传视频,有什么建议吗?
答案 0 :(得分:0)
async () => {
const uri = 'YOUR_IMAGE_URI';
const response = await fetch(uri);
const imgBlob = await response.blob();
return await fetch(SERVER_URL, {
method: 'PUT',
headers: {
'Content-Type': 'application/octet-stream',
},
body: imgBlob,
});
}
对于好奇的人,我使用react-native-image-picker来选择图像并获取其uri。