美文网首页RN 项目使用组件
ReactNative axios上传、下载图片

ReactNative axios上传、下载图片

作者: 精神病患者link常 | 来源:发表于2019-10-17 10:47 被阅读0次

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

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

相关文章

网友评论

    本文标题:ReactNative axios上传、下载图片

    本文链接:https://www.haomeiwen.com/subject/mibumctx.html