Home > Web Front-end > JS Tutorial > body text

react native uses fetch to upload images

php中世界最好的语言
Release: 2018-03-17 10:04:48
Original
2083 people have browsed it

This time I will bring you how to use fetch to upload pictures in react native. What are the precautions for using fetch to upload pictures in react native? The following is a practical case, let’s take a look.

Normal network

Request parameter is a JSON object

The request parameter for image upload uses the formData object

The code for uploading images using fetch is encapsulated as follows:

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);
      });
  });
}
Copy after login

Usage method

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=>{ 
     //请求失败
  })
Copy after login
Note: Due to different background server configurations,

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

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Several ways to bind this to react events

How to use characters in String.prototype.format String concatenation

Detailed explanation of implicit type conversion in JS

How to use $http service in angular

The above is the detailed content of react native uses fetch to upload images. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template