React Native上传图片

RN项目需要用到上传图片功能,整理一下做个记录。

插件选择是react-native-image-picker,还挺好用的,不过需要分ios和android不同平台去配置.

可以看看之前的文章https://segmentfault.com/a/11...

现在给出git上的react-native-image-picker地址

当你通过react-native-image-picker得到本地图片信息时执行以下代码:

处理单张图片

 let formData = new FormData();//如果需要上传多张图片,需要遍历数组,把图片的路径数组放入formData中
 let file = {uri: response.uri, type: 'multipart/form-data', name: 'image.png'};   //这里的key(uri和type和name)不能改变,
 formData.append("files",file);   //这里的files就是后台需要的key
 
 

多张图片处理

let formData = new FormData();

for(var i = 0;i<imgAry.length;i++){
    let file = {uri: imgAry[i], type: 'multipart/form-data', name: 'image.png'};   
    formData.append("files",file);  
}


上传

uploadURL上传图片的地址

 fetch(uploadURL,{
            method:'POST',
            headers:{
                'Content-Type':'multipart/form-data',
            },
            body:formData,
        })
            .then((response) => response.json())
            .then((responseData)=>{
                 let  source = ret.data.images[0].oUrl
                     console.log(source)  //得到的uri(http格式)拿到后进行操作吧
              
            })
            .catch((error)=>{console.error('error',error)});

下面是我自己应用的例子

引入模块和上传地址
clipboard.png

应用

clipboard.png

评论

暂无评论