RN 项目使用组件

ReactNative axios上传、下载图片

2019-10-17  本文已影响0人  精神病患者link常

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

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
}

下载图片

global.Buffer = global.Buffer || require('buffer').Buffer

  axios.get(imageUri,{responseType:'arraybuffer'})
  .then((response)=> Buffer.from(response.data, 'binary').toString('base64'))
  .then((res)=>{
    console.log('data:image/jpeg;base64,'+res);
  }).catch(e=>{
    console.log('eeee=',e);
  })

上一篇 下一篇

猜你喜欢

热点阅读