ReactNative axios上传、下载图片

上传文件(支持一次上传多个文件)

let axiosPostRequestCancel = null
function uploadFiles(data, progressCallBack, callBack) {
  let formData = new FormData();

  data.map((item,index)=>{
    let file = {
      uri: 本地文件绝对路径,
      type: 'application/octet-stream',
      name: 文件名字
    };
    formData.append("file", file);
  })
  let config = {
    //添加请求头
    headers: { "Content-Type": "multipart/form-data" },
    timeout: 600000,
    //添加上传进度监听事件
    onUploadProgress: e => {
      let completeProgress = (e.loaded / e.total * 100) | 0;
      progressCallBack && progressCallBack(completeProgress)
    },
    cancelToken: new axios.CancelToken(function executor(c) {
      axiosPostRequestCancel = c // 用于取消上传
    })
  };

  axios.post(接口地址, formData, config)
  .then(
    function (response)
    {
      callBack && callBack(true, response)
    })
    .catch(function (error) {
      callBack && callBack(false)
    });
}

/**
 * [cancelAxiosRequest 取消axios post请求]
 */
function cancelAxiosRequest(){
  axiosPostRequestCancel && axiosPostRequestCancel('cancel')
  axiosPostRequestCancel = null
}

下载图片

import Base64ToArraybuffer from 'base64-arraybuffer'
axios(imageUrl,{responseType: 'arraybuffer'})
    .then(function(response) {
      let base64 = Base64ToArraybuffer.encode(response.data)
      let imagePath = getImagePath(imageUrl)
      RNFS.writeFile(imagePath, base64, 'base64')
  });

你可能感兴趣的:(ReactNative axios上传、下载图片)