React Native uses fetch to implement sample code for Image Upload,
This article describes the sample code for React Native to use fetch to upload images. The Code is as follows:
Common network request parameters are JSON objects
The request parameter for Image Upload uses the formData object.
The Image Upload code using fetch is encapsulated 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 })
Note: Due to different backend server configurations,
Let file = {uri: params. path, type: 'application/octet-stream', name: 'image.jpg '} may also be multipart/form-data
The file field in formData. append ("file", file) may also be images
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.