美文网首页
React上传图片

React上传图片

作者: 我的钱包瘪瘪的 | 来源:发表于2019-10-22 10:48 被阅读0次

腾讯云上传图片

// react + antd-mobiled + 腾讯云上传图片

const appId = 31318;

import React, { Component } from "react";
import lrz from 'lrz';
import axios from 'axios'
import queryString from 'query-string';
// import ES6Promise from "es6-promise"
// ES6Promise.polyfill();
// axios的配置
const axiosInstance = axios.create({
    baseURL: '',
});

// 拦截request,设置全局请求为ajax请求
axiosInstance.interceptors.request.use(function (config) {  //配置发送请求的信息
    //设置默认请求头
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    config.timeout = config.timeout || 20000 // 超时设置
    if (config.method === 'post') {
        if(config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8'){
            config.data = queryString.stringify(config.data)
        }
    }
    return config
}, function (error) {
    return Promise.reject(error);
});
// 拦截响应response,并做一些错误处理
axiosInstance.interceptors.response.use((response) => {
    if(response.status  === 200 || response.status  === 206 || response.status  === 304){
        return response.data;
    }
    const data = response.data;
    const err = new Error(data.description);
    err.data = data;
    err.response = response;
    throw err;
}, (err) => { // 这里是返回状态码不为200时候的错误处理
    // console.log('路由跳轉');
    // console.log(err);
    // return err;
    return Promise.reject(err.response);
});

export default axiosInstance

// 封装请求方法
/**
 * 
 * @param {string} method 
 * @param {string} url 
 * @param {object} options axios基础配置
 */
const fetchData = (method='get', url='', options={}) => {
  /**
   * @param {object} data 请求参数
   * @param {object} config 自定义axios配置
   * @param {bool} needHandleCode 是否处理code
   */
  return ({data={}, config={}, needHandleCode=true} = {}) => {
      let params = {};
      if (method.toLowerCase() === 'get') {
          params = data;
      }
      if (method.toLowerCase() === "post") {
        config.headers = config.headers || {};
        config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/x-www-form-urlencoded;charset=UTF-8';
      }
      return axiosInstance({
          ...options, ...config, method, url, data, params,
      }).then(response => {
          // const code = response.code;
          // if(parseInt(code) !== 0 && code !== undefined){
          //     handleResponseCode(code, response, needHandleCode);
          // }
          return response;
      }).catch( err => {
          if(err){
              const res = {
                  code: null,
                  msg: window.navigator.onLine ? err.status + ' ' + err.statusText : '网络异常,请检查您的网络设置!',
              }
              // handleResponseCode(res.code, res, needHandleCode);
              return Promise.resolve(res);
          }
      })
  }
}

const option = { baseURL: '' } // http://200.200.200.230/hetapi/api/mock/27

const uploadFileToTencent = fetchData('post', `/v4/web/tencentcloud/upload`, option) // 腾讯云上传


class Image extends Component {
  constructor (props) {
    super(props)
    this.state = {
      headImgList: [{url: ''}],       // 上传的图片列表
      headImgLoading: false,          // 上传的loading
    }
  }
  // 图片处理公共方法
  handleCustomRequest = (fileData, callback) => {
    const formatReg = /\.(jpg|jpeg|png|gif)$/i
    if (fileData.file.size / 1024 / 1024 > 1) {
      Toast.info('上传图片过大', 3)
      return
    }

    if (fileData.file.name.search(formatReg) === -1) {
      Toast.info('请选择正确的文件类型', 3)
      return
    }
    const mediaFile = fileData.file
    const fileNameArray = mediaFile.name.split('.')
    const postfix = fileNameArray[fileNameArray.length - 1] //文件后缀名
    const fileName = new Date().getTime() + '.' + postfix //新的文件名
    const newFile = new File([mediaFile], fileName)
    const formData = new FormData()

    formData.append('appId', appId)
    formData.append('domain', 'skintest.hetyj.com')
    formData.append('file', newFile)
    // 
    uploadFileToTencent({
      data: formData,
      config: {
        processData: false,
        contentType: false,
        headers: { 'Content-Type': 'multipart/form-data' }
      }
    }).then(res => {
      if (res && res.code === 0) {
        if (typeof callback === 'function') {
          callback(res.data)
        }
      } else {
        Toast.info('上传图片失败', 3)
        callback()
      }
    })
  }
  // 压缩图片(大于1M), 然后再上传
  handleImgChange = (files, type) => {
    const { headImgList } = this.state
    if (type === 'add') {
      this.setState({ headImgLoading: true }, () => {
        const photoData = files[files.length - 1]
        // 大于1M的图片进行压缩, 小于的原图上传
        if (photoData.file.size / 1024 / 1024 > 1) {
          // 压缩图片的插件
          lrz(photoData.url, { quality: 0.1 })
            .then(rst => {
              // console.log('压缩之后图片大小(KB)', rst.fileLen / 1024)
              const fileData = {}
              const newFile = new File([rst.file], photoData.file.name)
              fileData.file = newFile
              fileData.url = rst.base64
              // console.log('拼凑出来的fileData对象', fileData);
              // 处理成功会执行, data.url即为上传之后的url
              this.handleCustomRequest(fileData, data => {
                if (data) {
                  // headImgList.push({ url: data.url });     // 上传多张, 且有上传按钮
                  headImgList[0] = { url: data.url }          // 上传1张, 且上传按钮覆盖在照片上方(透明)
                  this.setState(
                    { headImgList, headImgLoading: false },
                  )
                } else {
                  this.setState({ headImgLoading: false })
                }
              })
            })
            .catch(() => {
              this.setState({ headImgLoading: false })
            })
        } else {
          this.handleCustomRequest(photoData, data => {
            // headImgList.push({ url: data.url });
            headImgList[0] = { url: data.url }
            this.setState({ headImgList, headImgLoading: false }, () =>
              this.handleUpdateCustomerInfo(data.url)
            )
          })
        }
      })
    } else if (type === 'remove') {
      this.setState({ headImgList: files })
    }
  }
  render () {
    const { headImgList } = this.state;
    return (
      <ImagePicker
        className="data-manage-icon"
        files={headImgList}
        onChange={this.handleImgChange}
        onImageClick={(index, fs) => console.log(index, fs)}
        selectable={headImgList.length < 2}
        multiple={false}
        disableDelete={true}
      />
    )
  }
}
export default Image;


相关文章

网友评论

      本文标题:React上传图片

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