Home  >  Article  >  Web Front-end  >  How Native uses fetch to implement image upload function

How Native uses fetch to implement image upload function

php中世界最好的语言
php中世界最好的语言Original
2018-04-11 16:27:562104browse

This time I will show you how Native uses fetch to implement the image upload function. What are the precautions for Native to use fetch to implement the image upload function. The following is a practical case. , let’s take a look.

Normal networkRequest parameter is a JSON object

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);
      });
  });
}

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=>{ 
     //请求失败
  })

Note: Due to different background server configurations,
let file = {uri: params.path, type: 'application/octet-stream', name: ' The type in image.jpg'} may also be multipart/form-data
The file field in formData.append("file", file) 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:

How js implements A-Z sorting of Chinese Pinyin

vue.js moves the array position and updates it in real time View

#Vue handles the array page through the following table and does not render

The above is the detailed content of How Native uses fetch to implement image upload function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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