Home > Web Front-end > JS Tutorial > How React Native uses fetch to upload images

How React Native uses fetch to upload images

小云云
Release: 2018-03-09 09:53:53
Original
2375 people have browsed it

This article introduces the sample code of React Native using fetch to implement image upload, and shares it with everyone. The details are as follows: The ordinary network request parameter is a JSON object. The request parameter for image upload uses the formData object

The code package for using fetch to upload images is 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, the type in
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

Related recommendations:

Use express and Sharing tips on fetching local json files

React Native uses Fetch to send POST requests

Four fetch statements in php

The above is the detailed content of How 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