国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

react native實現往服務器上傳網絡圖片的實例

2019-11-19 15:53:38
字體:
來源:轉載
供稿:網友

如下所示:

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);      });  });

使用方法

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=>{      //請求失敗  })

注意點

let file = {uri: params.path, type: 'application/octet-stream', name: 'image.jpg'}中的type也可能是multipart/form-dataformData.append("file", file)中的的file字段也可能是images

普通網絡請求參數是JSON對象

圖片上傳的請求參數使用的是formData對象

總結:

React Native中雖然也內置了XMLHttpRequest 網絡請求API(也就是俗稱的ajax),但XMLHttpRequest 是一個設計粗糙的 API,不符合職責分離的原則,配置和調用方式非常混亂,而且基于事件的異步模型寫起來也沒有現代的 Promise 友好。而Fetch 的出現就是為了解決 XHR 的問題,所以react Native官方推薦使用Fetch API。

fetch請求示例如下:

return fetch('http://facebook.github.io/react-native/movies.json')  .then((response) => response.json())  .then((responseJson) => {   return responseJson.movies;  })  .catch((error) => {   console.error(error);  });

使用Promise封裝fetch請求

let common_url = 'http://192.168.1.1:8080/'; //服務器地址let token = '';  /** * @param {string} url 接口地址 * @param {string} method 請求方法:GET、POST,只能大寫 * @param {JSON} [params=''] body的請求參數,默認為空 * @return 返回Promise */function fetchRequest(url, method, params = ''){  let header = {    "Content-Type": "application/json;charset=UTF-8",    "accesstoken":token //用戶登陸后返回的token,某些涉及用戶數據的接口需要在header中加上token  };  console.log('request url:',url,params); //打印請求參數  if(params == ''){  //如果網絡請求中沒有參數    return new Promise(function (resolve, reject) {      fetch(common_url + url, {        method: method,        headers: header      }).then((response) => response.json())        .then((responseData) => {          console.log('res:',url,responseData); //網絡請求成功返回的數據          resolve(responseData);        })        .catch( (err) => {          console.log('err:',url, err);   //網絡請求失敗返回的數據              reject(err);        });    });  }else{  //如果網絡請求中帶有參數    return new Promise(function (resolve, reject) {      fetch(common_url + url, {        method: method,        headers: header,        body:JSON.stringify(params)  //body參數,通常需要轉換成字符串后服務器才能解析      }).then((response) => response.json())        .then((responseData) => {          console.log('res:',url, responseData);  //網絡請求成功返回的數據          resolve(responseData);        })        .catch( (err) => {          console.log('err:',url, err);  //網絡請求失敗返回的數據           reject(err);        });    });  }}

使用fetch請求,如果服務器返回的中文出現了亂碼,則可以在服務器端設置如下代碼解決:

produces="text/html;charset=UTF-8"

fetchRequest使用如下:GET請求:fetchRequest('app/book','GET')  .then( res=>{    //請求成功    if(res.header.statusCode == 'success'){      //這里設定服務器返回的header中statusCode為success時數據返回成功    }else{      //服務器返回異常,設定服務器返回的異常信息保存在 header.msgArray[0].desc      console.log(res.header.msgArray[0].desc);    }  }).catch( err=>{     //請求失敗  })POST請求:let params = {  username:'admin',  password:'123456'}fetchRequest('app/signin','POST',params)  .then( res=>{    //請求成功    if(res.header.statusCode == 'success'){      //這里設定服務器返回的header中statusCode為success時數據返回成功    }else{      //服務器返回異常,設定服務器返回的異常信息保存在 header.msgArray[0].desc       console.log(res.header.msgArray[0].desc);    }  }).catch( err=>{     //請求失敗  })

fetch超時處理

由于原生的Fetch API 并不支持timeout屬性,如果項目中需要控制fetch請求的超時時間,可以對fetch請求進一步封裝實現timeout功能,代碼如下:

fetchRequest超時處理封裝

/** * 讓fetch也可以timeout * timeout不是請求連接超時的含義,它表示請求的response時間,包括請求的連接、服務器處理及服務器響應回來的時間 * fetch的timeout即使超時發生了,本次請求也不會被abort丟棄掉,它在后臺仍然會發送到服務器端,只是本次請求的響應內容被丟棄而已 * @param {Promise} fetch_promise  fetch請求返回的Promise * @param {number} [timeout=10000]  單位:毫秒,這里設置默認超時時間為10秒 * @return 返回Promise */function timeout_fetch(fetch_promise,timeout = 10000) {  let timeout_fn = null;   //這是一個可以被reject的promise  let timeout_promise = new Promise(function(resolve, reject) {    timeout_fn = function() {      reject('timeout promise');    };  });  //這里使用Promise.race,以最快 resolve 或 reject 的結果來傳入后續綁定的回調  let abortable_promise = Promise.race([    fetch_promise,    timeout_promise  ]);  setTimeout(function() {    timeout_fn();  }, timeout);  return abortable_promise ;}let common_url = 'http://192.168.1.1:8080/'; //服務器地址let token = '';  /** * @param {string} url 接口地址 * @param {string} method 請求方法:GET、POST,只能大寫 * @param {JSON} [params=''] body的請求參數,默認為空 * @return 返回Promise */function fetchRequest(url, method, params = ''){  let header = {    "Content-Type": "application/json;charset=UTF-8",    "accesstoken":token //用戶登陸后返回的token,某些涉及用戶數據的接口需要在header中加上token  };  console.log('request url:',url,params); //打印請求參數  if(params == ''){  //如果網絡請求中沒有參數    return new Promise(function (resolve, reject) {      timeout_fetch(fetch(common_url + url, {        method: method,        headers: header      })).then((response) => response.json())        .then((responseData) => {          console.log('res:',url,responseData); //網絡請求成功返回的數據          resolve(responseData);        })        .catch( (err) => {          console.log('err:',url, err);   //網絡請求失敗返回的數據              reject(err);        });    });  }else{  //如果網絡請求中帶有參數    return new Promise(function (resolve, reject) {      timeout_fetch(fetch(common_url + url, {        method: method,        headers: header,        body:JSON.stringify(params)  //body參數,通常需要轉換成字符串后服務器才能解析      })).then((response) => response.json())        .then((responseData) => {          console.log('res:',url, responseData);  //網絡請求成功返回的數據          resolve(responseData);        })        .catch( (err) => {          console.log('err:',url, err);  //網絡請求失敗返回的數據           reject(err);        });    });  }}

以上這篇react native實現往服務器上傳網絡圖片的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 闽清县| 杭州市| 锡林浩特市| 甘德县| 穆棱市| 南宁市| 东明县| 阿拉善盟| 泸溪县| 马公市| 阿图什市| 新巴尔虎左旗| 山阳县| 班戈县| 贵溪市| 萨迦县| 宜黄县| 海口市| 广宗县| 乐至县| 介休市| 彝良县| 伊春市| 七台河市| 麟游县| 玛曲县| 新河县| 吉隆县| 泰顺县| 察隅县| 富蕴县| 华宁县| 安泽县| 盘锦市| 赤峰市| 岑巩县| 鹰潭市| 上高县| 鄄城县| 揭阳市| 齐河县|