Home >Web Front-end >JS Tutorial >react native uses fetch to upload images
This time I will bring you how to use fetch to upload pictures in react native. What are the precautions for using fetch to upload pictures in react native? The following is a practical case, let’s take a look.
Normal networkRequest parameter is a JSON object
The request parameter for image upload uses the formData objectThe code for uploading images using fetch is encapsulated as follows:
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); }); }); }
Usage method
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=>{ //请求失败 })Note: Due to different background server configurations,
let file = {uri : params.path, type: 'application/octet-stream', name: 'image.jpg'} may also be the type in multipart/form-data
formData.append("file", file) The file field may also be images
Several ways to bind this to react events
How to use characters in String.prototype.format String concatenation
Detailed explanation of implicit type conversion in JS
How to use $http service in angular
The above is the detailed content of react native uses fetch to upload images. For more information, please follow other related articles on the PHP Chinese website!