• <fieldset id="8imwq"><menu id="8imwq"></menu></fieldset>
  • <bdo id="8imwq"><input id="8imwq"></input></bdo>
    最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
    問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
    當前位置: 首頁 - 科技 - 知識百科 - 正文

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

    來源:懂視網 責編:小采 時間:2020-11-27 22:33:27
    文檔

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

    react native實現往服務器上傳網絡圖片的實例:如下所示: let common_url = 'http://192.168.1.1:8080/'; //服務器地址 let token = ''; //用戶登陸后返回的token /** * 使用fetch實現圖片上傳 * @param {string} url 接口地址 * @param {JSON} params body的
    推薦度:
    導讀react native實現往服務器上傳網絡圖片的實例:如下所示: let common_url = 'http://192.168.1.1:8080/'; //服務器地址 let token = ''; //用戶登陸后返回的token /** * 使用fetch實現圖片上傳 * @param {string} url 接口地址 * @param {JSON} params body的

    如下所示:

    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-data
    formData.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實現往服務器上傳網絡圖片的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

    聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

    文檔

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

    react native實現往服務器上傳網絡圖片的實例:如下所示: let common_url = 'http://192.168.1.1:8080/'; //服務器地址 let token = ''; //用戶登陸后返回的token /** * 使用fetch實現圖片上傳 * @param {string} url 接口地址 * @param {JSON} params body的
    推薦度:
    • 熱門焦點

    最新推薦

    猜你喜歡

    熱門推薦

    專題
    Top
    主站蜘蛛池模板: 亚洲综合一区二区精品导航| 精品久久香蕉国产线看观看亚洲| 久久久久久国产精品无码超碰| 在线电影国产精品| 精品卡一卡二卡乱码高清| 久久这里有精品视频| 国产成人精品大尺度在线观看| 成人国内精品久久久久影院| 无码少妇精品一区二区免费动态| 欧美午夜精品一区二区三区91 | 久久精品一区二区| 无码aⅴ精品一区二区三区浪潮 | 国产精品国产三级专区第1集| 亚洲欧美精品一区久久中文字幕 | 最新欧美性爱精品一区二区三区 | 91大神精品全国在线观看| 久久精品国产亚洲AV电影 | 国产999精品久久久久久| 国产精品2019| 国产精品无码一区二区三区电影| 亚洲综合精品香蕉久久网| 免费精品国自产拍在线播放 | 久久成人国产精品二三区| 成人国产精品免费视频| 久久99精品久久久久久久久久 | 国产日韩久久久精品影院首页 | 国产成人精品999在线观看| 99re6在线视频精品免费| 日本内射精品一区二区视频| 亚洲性日韩精品一区二区三区| 久久99精品久久久久久野外| 国产精品亚洲视频| 欧美精品黑人粗大免费| 在线观看亚洲精品福利片| 亚洲国产成人乱码精品女人久久久不卡 | 久久99国产精品成人欧美| 国产在线精品观看免费观看| 精品99又大又爽又硬少妇毛片| 精品国产黑色丝袜高跟鞋| 欧美成人精品网站播放 | 精品久久综合1区2区3区激情|