圖片上傳實作
let common_url = 'https://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 物件。
總結:為什麼用 fetch
React Native 雖然內建了 XMLHttpRequest(也就是俗稱的 ajax),但 XHR 是個設計粗糙的 API,不符合職責分離原則,設定與呼叫方式相當混亂,而且基於事件的異步模型寫起來遠不如 Promise 友好。fetch 的出現正是為了解決 XHR 的這些問題,因此官方推薦使用。
fetch 基本用法
return fetch('https://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 = 'https://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 並不支援 timeout 屬性。若專案需要控制請求超時時間,就得進一步封裝。
加入超時控制的封裝
/** * 讓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 = 'https://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); }); }); } }
以上就是這次分享的全部內容,希望對你的開發有所幫助。