react native實(shí)現(xiàn)往服務(wù)器上傳網(wǎng)絡(luò)圖片的實(shí)例
如下所示:
let common_url = 'http://192.168.1.1:8080/'; //服務(wù)器地址 let token = ''; //用戶登陸后返回的token /** * 使用fetch實(shí)現(xiàn)圖片上傳 * @param {string} url 接口地址 * @param {JSON} params body的請求參數(shù) * @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'){ //這里設(shè)定服務(wù)器返回的header中statusCode為success時(shí)數(shù)據(jù)返回成功 upLoadImgUrl = res.body.imgurl; //服務(wù)器返回的地址 }else{ //服務(wù)器返回異常,設(shè)定服務(wù)器返回的異常信息保存在 header.msgArray[0].desc console.log(res.header.msgArray[0].desc); } }).catch( err=>{ //請求失敗 })
注意點(diǎn)
let file = {uri: params.path, type: 'application/octet-stream', name: 'image.jpg'}中的type也可能是multipart/form-data formData.append("file", file)中的的file字段也可能是images
普通網(wǎng)絡(luò)請求參數(shù)是JSON對象
圖片上傳的請求參數(shù)使用的是formData對象
總結(jié):
React Native中雖然也內(nèi)置了XMLHttpRequest 網(wǎng)絡(luò)請求API(也就是俗稱的ajax),但XMLHttpRequest 是一個(gè)設(shè)計(jì)粗糙的 API,不符合職責(zé)分離的原則,配置和調(diào)用方式非?;靵y,而且基于事件的異步模型寫起來也沒有現(xiàn)代的 Promise 友好。而Fetch 的出現(xiàn)就是為了解決 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/'; //服務(wù)器地址 let token = ''; /** * @param {string} url 接口地址 * @param {string} method 請求方法:GET、POST,只能大寫 * @param {JSON} [params=''] body的請求參數(shù),默認(rèn)為空 * @return 返回Promise */ function fetchRequest(url, method, params = ''){ let header = { "Content-Type": "application/json;charset=UTF-8", "accesstoken":token //用戶登陸后返回的token,某些涉及用戶數(shù)據(jù)的接口需要在header中加上token }; console.log('request url:',url,params); //打印請求參數(shù) if(params == ''){ //如果網(wǎng)絡(luò)請求中沒有參數(shù) 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); //網(wǎng)絡(luò)請求成功返回的數(shù)據(jù) resolve(responseData); }) .catch( (err) => { console.log('err:',url, err); //網(wǎng)絡(luò)請求失敗返回的數(shù)據(jù) reject(err); }); }); }else{ //如果網(wǎng)絡(luò)請求中帶有參數(shù) return new Promise(function (resolve, reject) { fetch(common_url + url, { method: method, headers: header, body:JSON.stringify(params) //body參數(shù),通常需要轉(zhuǎn)換成字符串后服務(wù)器才能解析 }).then((response) => response.json()) .then((responseData) => { console.log('res:',url, responseData); //網(wǎng)絡(luò)請求成功返回的數(shù)據(jù) resolve(responseData); }) .catch( (err) => { console.log('err:',url, err); //網(wǎng)絡(luò)請求失敗返回的數(shù)據(jù) reject(err); }); }); } }
使用fetch請求,如果服務(wù)器返回的中文出現(xiàn)了亂碼,則可以在服務(wù)器端設(shè)置如下代碼解決:
produces="text/html;charset=UTF-8"
fetchRequest使用如下: GET請求: fetchRequest('app/book','GET') .then( res=>{ //請求成功 if(res.header.statusCode == 'success'){ //這里設(shè)定服務(wù)器返回的header中statusCode為success時(shí)數(shù)據(jù)返回成功 }else{ //服務(wù)器返回異常,設(shè)定服務(wù)器返回的異常信息保存在 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'){ //這里設(shè)定服務(wù)器返回的header中statusCode為success時(shí)數(shù)據(jù)返回成功 }else{ //服務(wù)器返回異常,設(shè)定服務(wù)器返回的異常信息保存在 header.msgArray[0].desc console.log(res.header.msgArray[0].desc); } }).catch( err=>{ //請求失敗 })
fetch超時(shí)處理
由于原生的Fetch API 并不支持timeout屬性,如果項(xiàng)目中需要控制fetch請求的超時(shí)時(shí)間,可以對fetch請求進(jìn)一步封裝實(shí)現(xiàn)timeout功能,代碼如下:
fetchRequest超時(shí)處理封裝
/** * 讓fetch也可以timeout * timeout不是請求連接超時(shí)的含義,它表示請求的response時(shí)間,包括請求的連接、服務(wù)器處理及服務(wù)器響應(yīng)回來的時(shí)間 * fetch的timeout即使超時(shí)發(fā)生了,本次請求也不會被abort丟棄掉,它在后臺仍然會發(fā)送到服務(wù)器端,只是本次請求的響應(yīng)內(nèi)容被丟棄而已 * @param {Promise} fetch_promise fetch請求返回的Promise * @param {number} [timeout=10000] 單位:毫秒,這里設(shè)置默認(rèn)超時(shí)時(shí)間為10秒 * @return 返回Promise */ function timeout_fetch(fetch_promise,timeout = 10000) { let timeout_fn = null; //這是一個(gè)可以被reject的promise let timeout_promise = new Promise(function(resolve, reject) { timeout_fn = function() { reject('timeout promise'); }; }); //這里使用Promise.race,以最快 resolve 或 reject 的結(jié)果來傳入后續(xù)綁定的回調(diào) 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/'; //服務(wù)器地址 let token = ''; /** * @param {string} url 接口地址 * @param {string} method 請求方法:GET、POST,只能大寫 * @param {JSON} [params=''] body的請求參數(shù),默認(rèn)為空 * @return 返回Promise */ function fetchRequest(url, method, params = ''){ let header = { "Content-Type": "application/json;charset=UTF-8", "accesstoken":token //用戶登陸后返回的token,某些涉及用戶數(shù)據(jù)的接口需要在header中加上token }; console.log('request url:',url,params); //打印請求參數(shù) if(params == ''){ //如果網(wǎng)絡(luò)請求中沒有參數(shù) 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); //網(wǎng)絡(luò)請求成功返回的數(shù)據(jù) resolve(responseData); }) .catch( (err) => { console.log('err:',url, err); //網(wǎng)絡(luò)請求失敗返回的數(shù)據(jù) reject(err); }); }); }else{ //如果網(wǎng)絡(luò)請求中帶有參數(shù) return new Promise(function (resolve, reject) { timeout_fetch(fetch(common_url + url, { method: method, headers: header, body:JSON.stringify(params) //body參數(shù),通常需要轉(zhuǎn)換成字符串后服務(wù)器才能解析 })).then((response) => response.json()) .then((responseData) => { console.log('res:',url, responseData); //網(wǎng)絡(luò)請求成功返回的數(shù)據(jù) resolve(responseData); }) .catch( (err) => { console.log('err:',url, err); //網(wǎng)絡(luò)請求失敗返回的數(shù)據(jù) reject(err); }); }); } }
以上這篇react native實(shí)現(xiàn)往服務(wù)器上傳網(wǎng)絡(luò)圖片的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
react16.8.0以上MobX在hook中的使用方法詳解
這篇文章主要為大家介紹了react16.8.0以上MobX在hook中的使用方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07如何使用 React Native WebView 實(shí)現(xiàn) App&nb
通過 react-native-webview,我們可以輕松實(shí)現(xiàn) App 與 Web 的雙向通訊,這種技術(shù)非常適合需要在移動應(yīng)用中嵌入復(fù)雜網(wǎng)頁功能的場景,感興趣的朋友一起看看吧2024-12-12React.memo函數(shù)中的參數(shù)示例詳解
這篇文章主要為大家介紹了React.memo函數(shù)中的參數(shù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09React?Router掌握路由搭建與權(quán)限管控的操作方法(?從入門到精通)
本文詳細(xì)介紹了React?Router庫在React應(yīng)用開發(fā)中的應(yīng)用,包括其核心功能、安裝使用、基礎(chǔ)使用、核心組件和功能、路由參數(shù)和嵌套路由、編程式導(dǎo)航以及路由權(quán)限管理等方面,感興趣的朋友一起看看吧2025-01-01React+TypeScript+webpack4多入口配置詳解
這篇文章主要介紹了React+TypeScript+webpack4多入口配置詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08解決react中l(wèi)abel標(biāo)簽for報(bào)錯(cuò)問題
這篇文章主要介紹了react中l(wèi)abel標(biāo)簽for報(bào)錯(cuò)問題,解決辦法就是react中l(wèi)abel標(biāo)簽沒有for屬性,用htmlFor代替for屬性,感興趣的朋友跟隨小編一起看看吧2022-02-02