React native allows you to upload network images to servers,

Source: Internet
Author: User

React native allows you to upload network images to servers,

As follows:

Let common_url = 'HTTP: // 192.168.1.1: 8080/'; // The server address let token = ''; // The token/*** returned by the user after login uses fetch to upload images * @ param {string} url interface address * @ param {JSON} params body request parameter * @ 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 ('uploadimag', responseData); resolve (responseData );}). catch (err) => {console. log ('err', err); reject (err );});});

Usage

Let params = {userId: 'abc12345', // user ID path: 'file: /// storage/emulated/0/Pictures/image.jpg '// local file address} uploadImage ('app/uploadfile', params ). then (res => {// if (res. header. statusCode = 'success ') {// set statusCode in the header returned by the server to success. When the returned data is successful, upLoadImgUrl = res. body. imgurl; // The address returned by the server} else {// The server returns an exception and sets the exception information returned by the server to be saved in the header. msgArray [0]. desc console. log (res. header. msgArray [0]. desc );}}). catch (err =>{// request failed })

Notes

Let file = {uri: params. path, type: 'application/octet-stream', name: 'image.jpg '} may also be the file field in multipart/form-dataformData.append ("file", file) or images

Common network request parameters are JSON objects

The request parameter for Image Upload uses the formData object.

Summary:

Although the XMLHttpRequest network request API (also known as ajax) is built in React Native, XMLHttpRequest is a poorly designed API that does not conform to the principle of separation of duties, the configuration and call methods are messy, and the event-based Asynchronous model is not as friendly as the modern Promise. Fetch is used to solve the XHR problem. Therefore, the Fetch API is recommended for react Native.

Example of a fetch request:

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

Use Promise to encapsulate fetch requests

Let common_url = 'HTTP: // 192.168.1.1: 8080/'; // The server address let token = ''; /*** @ param {string} url interface address * @ param {string} method: GET, POST, only Request Parameters of @ param {JSON} [params = ''] body can be capitalized. The default value is null. * @ return returns Promise */function fetchRequest (url, method, params = '') {let header = {" Content-Type ":" application/json; charset = UTF-8 "," accesstoken ": token // the token returned after the user logs in, some interfaces involving user data must be added with token} in the header; console. log ('request url: ', url, params); // print the request parameter if (params = '') {// if there is no return new Promise (function (resolve, reject) {fetch (common_url + url, {method: method, headers: header}) in the network request }). then (response) => response. json ()). then (responseData) => {console. log ('res: ', url, responseData); // resolve (responseData) returned when the network request is successful );}). catch (err) => {console. log ('err: ', url, err); // reject (err) ;}) returned when a network request fails );});});} else {// if the network request contains the return new Promise (function (resolve, reject) {fetch (common_url + url, {method: method, headers: header, body: JSON. stringify (params) // body parameter, which must be converted to a string before the server can parse }). then (response) => response. json ()). then (responseData) => {console. log ('res: ', url, responseData); // resolve (responseData) returned when the network request is successful );}). catch (err) => {console. log ('err: ', url, err); // reject (err) ;}) returned when a network request fails );});});}}

If the Chinese characters returned by the server contain garbled characters, you can set the following code on the server:

Produces = "text/html; charsets = UTF-8"

FetchRequest uses the following: GET request: fetchRequest ('app/Book', 'get '). then (res => {// if (res. header. statusCode = 'success ') {// set statusCode in the header returned by the server to return data success when success} else {// The server returns an exception, set the exception information returned by the server to be saved in the header. msgArray [0]. desc console. log (res. header. msgArray [0]. desc );}}). catch (err =>{// request failed}) POST request: let params = {username: 'admin', password: '000000'} fetchRequest ('app/signin ', 'post', params ). then (res => {// if (res. header. statusCode = 'success ') {// set statusCode in the header returned by the server to return data success when success} else {// The server returns an exception, set the exception information returned by the server to be saved in the header. msgArray [0]. desc console. log (res. header. msgArray [0]. desc );}}). catch (err =>{// request failed })

Fetch timeout Processing

Because the native Fetch API does not support the timeout attribute, if you need to control the time-out time of the fetch request in the project, you can further encapsulate the fetch request to implement the timeout function. The Code is as follows:

FetchRequest timeout processing Encapsulation

/*** Allow fetch to also timeout * timeout is not the meaning of request connection timeout, it indicates the request's response time, including the request connection, server processing, and server response time * timeout of fetch. Even if a timeout occurs, this request will not be discarded by abort and will still be sent to the server in the background, only the response content of this request is discarded * @ param {Promise} fetch_promise Promise returned by the fetch Request * @ param {number} [timeout = 10000] Unit: millisecond, set the default timeout value to 10 seconds * @ return to return Promise */function timeout_fetch (fetch_promise, timeout = 10000) {let timeout_fn = null; // This Is A reject-enabled promise let timeout_promise = new Promise (function (resolve, reject) {timeout_fn = function () {reject ('timeout promise ') ;};}); // use Promise here. race, passed in the callback let abortable_promise = Promise to be bound with the fastest resolve or reject results. race ([fetch_promise, timeout_promise]); setTimeout (function () {timeout_fn () ;}, timeout); return abortable_promise;} let common_url = 'HTTP: // 192.168.1.1: 8080/'; // server address let token = '';/*** @ param {string} url interface address * @ param {string} method Request method: GET, POST, only Request Parameters of @ param {JSON} [params = ''] body can be capitalized. The default value is null. * @ return returns Promise */function fetchRequest (url, method, params = '') {let header = {" Content-Type ":" application/json; charset = UTF-8 "," accesstoken ": token // the token returned after the user logs in, some interfaces involving user data must be added with token} in the header; console. log ('request url: ', url, params); // print the request parameter if (params = '') {// if there is no return new Promise (function (resolve, reject) {timeout_fetch (fetch (common_url + url, {method: method, headers: header}) parameter in the network request })). then (response) => response. json ()). then (responseData) => {console. log ('res: ', url, responseData); // resolve (responseData) returned when the network request is successful );}). catch (err) => {console. log ('err: ', url, err); // reject (err) ;}) returned when a network request fails );});});} else {// if the network request contains the return new Promise (function (resolve, reject) {timeout_fetch (fetch (common_url + url, {method: method, headers: header, body: JSON. stringify (params) // body parameter, which usually needs to be converted to a string before the server can parse })). then (response) => response. json ()). then (responseData) => {console. log ('res: ', url, responseData); // resolve (responseData) returned when the network request is successful );}). catch (err) => {console. log ('err: ', url, err); // reject (err) ;}) returned when a network request fails );});});}}

The above example of the react native Implementation of uploading network images to the server is all the content shared by Alibaba Cloud xiaobian. I hope to give you a reference and support for the customer's house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.