Home > Web Front-end > JS Tutorial > About using fetch to upload images in React Native (detailed tutorial)

About using fetch to upload images in React Native (detailed tutorial)

亚连
Release: 2018-06-01 09:11:45
Original
2102 people have browsed it

This article mainly introduces the sample code of React Native using fetch to upload images. Now I share it with you and give it as a reference.

This article introduces the sample code for React Native to use fetch to upload images, and shares it with everyone. The details are as follows:

Ordinary network request parameters are JSON objects

The request parameters for image upload use the formData object

Use fetch to upload the image code encapsulation 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

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, The type in 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 what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

JQuery selects the selected value method of the select component

$set and array in vue.js Update method_vue.js

Vue and vue-i18n are combined to implement multi-language switching method of background data

The above is the detailed content of About using fetch to upload images in React Native (detailed tutorial). 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