React Native使用fetch实现图片上传

来源:互联网 发布:最后免费升级windows 编辑:程序博客网 时间:2024/05/14 06:17

关于 React Native 网络请求的封装,可以参考我写的文章:http://blog.csdn.net/withings/article/details/71363433

React Native 网络请求封装:使用Promise封装fetch请求

普通网络请求参数是JSON对象 
图片上传的请求参数使用的是formData对象

fetch实现图片上传代码如下:

let common_url = 'http://192.168.1.1:8080/';  //服务器地址let token = '';   //用户登陆后返回的token/**  * 使用fetch实现图片上传 * @param {string} url  接口地址 * @param {JSON} params body的请求参数 * @return 返回Promise  */function uploadImage(url,params){    return new Promise(function (resolve, reject) {        let formData = new FormData();        for (var key in params){            formData.append(key, params[key]);        }        let file = {uri: params.path, type: 'application/octet-stream', name: 'image.jpg'};        formData.append("file", file);        fetch(common_url + url, {            method: 'POST',            headers: {                'Content-Type': 'multipart/form-data;charset=utf-8',                "x-access-token": token,            },            body: formData,        }).then((response) => response.json())            .then((responseData)=> {                console.log('uploadImage', responseData);                resolve(responseData);            })            .catch((err)=> {                console.log('err', err);                reject(err);            });    });}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

使用方法

let params = {    userId:'abc12345',   //用户id    path:'file:///storage/emulated/0/Pictures/image.jpg'    //本地文件地址}uploadImage('app/uploadFile',params )    .then( res=>{        //请求成功        if(res.header.statusCode == 'success'){            //这里设定服务器返回的header中statusCode为success时数据返回成功            upLoadImgUrl = res.body.imgurl;  //服务器返回的地址        }else{             //服务器返回异常,设定服务器返回的异常信息保存在 header.msgArray[0].desc            console.log(res.header.msgArray[0].desc);        }    }).catch( err=>{          //请求失败    })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

注意:由于后台服务器配置的不同, 
let file = {uri: params.path, type: 'application/octet-stream', name: 'image.jpg'}中的type也可能是multipart/form-data 
formData.append("file", file)中的的file字段也可能是images