react-native 图片选取与上传
首页 专栏 react-native 文章详情
0

react-native 图片选取与上传

汽水 发布于 4 月 15 日
安装图片选择插件
react-native-syan-image-picker 或 react-native-image-crop-picker,0.6以上版本无需手动link,具体插件配置参考GitHub链接 本次需求有多选功能 选取使用react-native-syan-image-picker
示例代码: const [imageList, setImageList] = useState<UploadFileResItem[]>([]); // 插件配置参数 具体参见插件配置文档 const options = { imageCount: 6, isCrop: false, }; // 用户点击按钮选取图片 const selectImage = () => { SyanImagePicker.asyncShowImagePicker(options) .then((photos: SelectedPhoto[]) => { // 处理选取结果 结果包含本地文件路径 // 由于后端 不支持多文件同时上传使用promise all完成多次上传请求 const fetchList = photos.map((item) => upload(item)); Promise.all(fetchList).then((res) => { setImageList((v) => [...v, ...res]); }); }) .catch((err) => { console.log('err', err); // 取消选择,err.message为"取消" }); }; const upload = (data: SelectedPhoto) => { const formData = new FormData(); formData.append('file', { uri: data.uri, // 本地文件路径 type: 'multipart/form-data', name: 'xxxx.jpg', // 图片名称 }); return uploadImage(formData).then((res) => res.data); };

注意事项

上传过程中不要使用react-native-debugger调试,react-native-debugger会将formdata内容转换为string,造成上传失败,建议使用flipper观察请求

react-native
阅读 107 发布于 4 月 15 日
举报
收藏
分享
本作品系原创, 采用《署名-非商业性使用-禁止演绎 4.0 国际》许可协议
avatar
汽水
3 声望
0 粉丝
关注作者
0 条评论
得票数 最新
提交评论
avatar
汽水
3 声望
0 粉丝
关注作者
宣传栏
目录
安装图片选择插件
react-native-syan-image-picker 或 react-native-image-crop-picker,0.6以上版本无需手动link,具体插件配置参考GitHub链接 本次需求有多选功能 选取使用react-native-syan-image-picker
示例代码: const [imageList, setImageList] = useState<UploadFileResItem[]>([]); // 插件配置参数 具体参见插件配置文档 const options = { imageCount: 6, isCrop: false, }; // 用户点击按钮选取图片 const selectImage = () => { SyanImagePicker.asyncShowImagePicker(options) .then((photos: SelectedPhoto[]) => { // 处理选取结果 结果包含本地文件路径 // 由于后端 不支持多文件同时上传使用promise all完成多次上传请求 const fetchList = photos.map((item) => upload(item)); Promise.all(fetchList).then((res) => { setImageList((v) => [...v, ...res]); }); }) .catch((err) => { console.log('err', err); // 取消选择,err.message为"取消" }); }; const upload = (data: SelectedPhoto) => { const formData = new FormData(); formData.append('file', { uri: data.uri, // 本地文件路径 type: 'multipart/form-data', name: 'xxxx.jpg', // 图片名称 }); return uploadImage(formData).then((res) => res.data); };

注意事项

上传过程中不要使用react-native-debugger调试,react-native-debugger会将formdata内容转换为string,造成上传失败,建议使用flipper观察请求