import React, { Component } from "react"; import Taro from '@tarojs/taro'; import { Text, View } from "@tarojs/components"; import { AtImagePicker, AtToast } from "taro-ui"; import './index.less'; import 'taro-ui/dist/style/components/image-picker.scss'; import 'taro-ui/dist/style/components/icon.scss'; import 'taro-ui/dist/style/components/toast.scss'; import 'taro-ui/dist/style/components/icon.scss'; import getBaseUrl from "../../../utils/servers/baseUrl"; class ImagePicker extends Component { constructor(props) { super(props); this.state = { files: props.files || [], speedProgress: 0, loading: false } this.onImgChange = this.onImgChange.bind(this); this.onFail = this.onFail.bind(this); this.onImageClick = this.onImageClick.bind(this); } onImgChange(files, operationType, index, type) { const BASE_URL = getBaseUrl(this.props.url); let token = Taro.getStorageSync('token'); let _this = this; if (operationType === 'remove') { let filesArr = files.concat([]); this.props.onChange(index, 'remove'); this.setState({ files: filesArr }) } else { let fileArr = this.state.files.concat([]); let arr = type === 'camera' ? files : files.splice(fileArr.length, files.length - fileArr.length) this.setState({ loading: true }) for (let i = 0; i < arr.length; i++) { const uploadTask = Taro.uploadFile({ url: BASE_URL + this.props.url, //仅为示例,非真实的接口地址 filePath: arr[i].url, name: 'file', header: { 'Accept': 'application/json, text/javascript,', 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Authorization': token }, success: function (res) { let dataJson = JSON.parse(res.data) if (dataJson.code == 200) { _this.props.onChange(dataJson.imgUrl, 'add'); _this.state.files.push(arr[i]); _this.setState({ files: _this.state.files }) } else { Taro.showToast({ title: dataJson.msg, icon: 'none' }) if (dataJson.code === '403') { _this.setState({ loading: false }) Taro.reLaunch({ url: '/pages/login/index' }) } } }, fail: function (err) { Taro.showToast({ title: '系统错误,请稍后重试', icon: 'none' }); }, complete: function (v) { //console.log(v) } }) uploadTask.progress((res) => { if (res.progress === 100) { let num = this.state.speedProgress + 1; let speed = num / arr.length * 100; this.setState({ speedProgress: num, }, () => { if (speed === 100) { setTimeout(() => { _this.setState({ speedProgress: 0, loading: false }) }, 1200) } }) } //console.log('上传进度', res.progress) //console.log('已经上传的数据长度', res.totalBytesSent) //console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend) }) } } } onFail() { } onImageClick(index) { let arr = []; for (let i of this.state.files) { arr.push(i.url) } Taro.previewImage({ current: arr[index], // 当前显示图片的http链接 urls: arr // 需要预览的图片http链接列表 }) } clear() { this.setState({ files: [] }) } render() { return ( <> ) } } export default ImagePicker;