提交 4da6c493 authored 作者: 钟是志's avatar 钟是志

34049 [离校]学生登录-学生处分中上次图片后不能正常提交【522622200506284524 123456】

上级 7e192255
import React, { Component } from 'react'; import React, {Component} from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { ImagePicker, Toast } from 'antd-mobile'; import {ImagePicker, Toast} from 'antd-mobile';
import config from '@/config/config'; import config from '@/config/config';
import { getToken } from '@/H5Public/utils/authority'; import {getToken} from '@/H5Public/utils/authority';
/** /**
* 组件使用方法 * 组件使用方法
* *
* <Upload * <Upload
ref='upload' this.refs.upload.handleSubmit() 调用子组件提交方法 ref='upload' this.refs.upload.handleSubmit() 调用子组件提交方法
handleSubmit={this.submit1} 子组件提交后返回后端数据回调函数 handleSubmit={this.submit1} 子组件提交后返回后端数据回调函数
// rest={{disableDelete:true}} 基于antd-mobile,可使用antd自身属性---不是必填项 // rest={{disableDelete:true}} 基于antd-mobile,可使用antd自身属性---不是必填项
/> />
*/ */
// 全局loadinng // 全局loadinng
let loadingCount = 0; let loadingCount = 0;
class Upload extends Component { class Upload extends Component {
constructor(props) { constructor(props) {
super(props) super(props)
this.state = { this.state = {
files: [], // 图片文件 files: [], // 图片文件
urlList: [] // 后端返回图片地址 urlList: [] // 后端返回图片地址
}
}
componentDidMount(){
// 回显
const ImageArr=[];
this.props.defaultFiles.map(item=>{
ImageArr.push({
url:item
})
})
this.setState({files:ImageArr})
} }
}
// 图片压缩函数 componentDidMount() {
zipImage = (file) => { // 回显
let fileSizeMb = file.size / 1024 / 1024; const ImageArr = [];
let fileName = file.name; this.props.defaultFiles.map(item => {
if (fileSizeMb < this.props.fileSizeMb) { // 1MB 以下的图片不需要压缩。 ImageArr.push({
this.uploadCall(file) url: item
return false; })
} })
let reader = new FileReader(); this.setState({files: ImageArr})
reader.readAsDataURL(file); }
reader.onload = (e) => {
//这里的e.target.result就是转换后base64格式的图片文件
let image = new Image(); //新建一个img标签(还没嵌入DOM节点)
image.src = e.target.result;
return image.onload = () => {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
let imageWidth = image.width * 0.3; //压缩后图片的大小
let imageHeight = image.height * 0.3;
let data = '';
canvas.width = imageWidth;
canvas.height = imageHeight;
context.drawImage(image, 0, 0, imageWidth, imageHeight); // 图片压缩函数
data = canvas.toDataURL('image/jpeg'); zipImage = (file) => {
let zipFile = this.dataURLtoFile(data, fileName); let fileSizeMb = file.size / 1024 / 1024;
this.uploadCall(zipFile) let fileName = file.name;
}; if (fileSizeMb < this.props.fileSizeMb) { // 1MB 以下的图片不需要压缩。
}; this.uploadCall(file)
}; return false;
//将base64转换为文件 }
dataURLtoFile = (dataurl, filename) => { let reader = new FileReader();
let arr = dataurl.split(','); reader.readAsDataURL(file);
let mime = arr[0].match(/:(.*?);/)[1]; reader.onload = (e) => {
//这里的e.target.result就是转换后base64格式的图片文件
let image = new Image(); //新建一个img标签(还没嵌入DOM节点)
image.src = e.target.result;
return image.onload = () => {
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
let imageWidth = image.width * 0.3; //压缩后图片的大小
let imageHeight = image.height * 0.3;
let data = '';
canvas.width = imageWidth;
canvas.height = imageHeight;
let bstr = atob(arr[1]); context.drawImage(image, 0, 0, imageWidth, imageHeight);
let n = bstr.length; data = canvas.toDataURL('image/jpeg');
let u8arr = new Uint8Array(n); let zipFile = this.dataURLtoFile(data, fileName);
while (n--) { this.uploadCall(zipFile)
u8arr[n] = bstr.charCodeAt(n); };
}
return new File([u8arr], filename, { type: mime });
}; };
// 上传本地 };
onChange = (files) => { //将base64转换为文件
this.setState({ files }); dataURLtoFile = (dataurl, filename) => {
} let arr = dataurl.split(',');
// 上传图片--方法 let mime = arr[0].match(/:(.*?);/)[1];
uploadImg = (file, callback) => {
const xhr = new XMLHttpRequest(); let bstr = atob(arr[1]);
const formData = new FormData(); let n = bstr.length;
formData.append('file', file); let u8arr = new Uint8Array(n);
xhr.open('post', config.uploadUrl + "?token=" + getToken(), true); while (n--) {
xhr.setRequestHeader("Accept", "application/json;charset=UTF-8"); u8arr[n] = bstr.charCodeAt(n);
xhr.send(formData);
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
const json = JSON.parse(xhr.responseText);
callback(json.url)
}
}
} }
// 上传后获取后端返回图片地址 return new File([u8arr], filename, {type: mime});
uploadCall = (item) => ( };
this.uploadImg(item, (res) => { // 上传本地
this.setState({ urlList: [...this.state.urlList, res] }, () => { onChange = (files) => {
if (this.state.files.length === this.state.urlList.length) { this.setState({files});
Toast.hide() }
loadingCount = 0; // 上传图片--方法
const {handleSubmit,labelId=''}=this.props; uploadImg = (file, callback) => {
handleSubmit(this.state.urlList,labelId) // 把后端返回url传给父组件 const xhr = new XMLHttpRequest();
} const formData = new FormData();
}) formData.append('file', file);
}) if(config.version === 'bdk'){
) xhr.open('post', config.uploadUrl, true);
// 提交 }else{
handleSubmit = () => { xhr.open('post', config.uploadUrl + "?token=" + getToken(), true);
const { files } = this.state;
Toast.loading('Loading...', 0);
// 判断是否是回显的图片--不是则进行压缩
const httpFiles=files.filter(item=>item.url.startsWith('http')) // 回显图片
const oldUrlArr=[];
httpFiles.map(item=>oldUrlArr.push(item.url))
const Files=files.filter(item => !item.url.startsWith('http')) // 本地图片
this.setState({urlList:oldUrlArr},()=>{
if(Files.length==0){
Toast.hide()
loadingCount = 0;
const {handleSubmit,labelId=''}=this.props;
handleSubmit(this.state.urlList,labelId) // 把后端返回url传给父组件
}
Files.map(item => {
loadingCount++
this.zipImage(item.file)
})
})
} }
render() { xhr.setRequestHeader("Accept", "application/json;charset=UTF-8");
const { files } = this.state; xhr.setRequestHeader("Authorization", `bearer ${getToken()}`);
const {multiple,accept,length,readOnly,rest}=this.props; xhr.send(formData);
return ( xhr.onreadystatechange = () => {
<div> if (xhr.readyState == 4 && xhr.status === 200) {
<ImagePicker const json = JSON.parse(xhr.responseText);
files={files} callback(json.url)
accept={accept} }
onChange={this.onChange}
selectable={readOnly?false:(files.length < length)}
multiple={multiple}
disableDelete={readOnly?true:false}
{...rest}
/>
</div>
);
} }
}
// 上传后获取后端返回图片地址
uploadCall = (item) => (
this.uploadImg(item, (res) => {
this.setState({urlList: [...this.state.urlList, res]}, () => {
if (this.state.files.length === this.state.urlList.length) {
Toast.hide()
loadingCount = 0;
const {handleSubmit, labelId = ''} = this.props;
handleSubmit(this.state.urlList, labelId) // 把后端返回url传给父组件
}
})
})
)
// 提交
handleSubmit = () => {
const {files} = this.state;
Toast.loading('Loading...', 0);
// 判断是否是回显的图片--不是则进行压缩
const httpFiles = files.filter(item => item.url.startsWith('http')) // 回显图片
const oldUrlArr = [];
httpFiles.map(item => oldUrlArr.push(item.url))
const Files = files.filter(item => !item.url.startsWith('http')) // 本地图片
this.setState({urlList: oldUrlArr}, () => {
if (Files.length == 0) {
Toast.hide()
loadingCount = 0;
const {handleSubmit, labelId = ''} = this.props;
handleSubmit(this.state.urlList, labelId) // 把后端返回url传给父组件
}
Files.map(item => {
loadingCount++
this.zipImage(item.file)
})
})
}
render() {
const {files} = this.state;
const {multiple, accept, length, readOnly, rest} = this.props;
return (
<div>
<ImagePicker
files={files}
accept={accept}
onChange={this.onChange}
selectable={readOnly ? false : (files.length < length)}
multiple={multiple}
disableDelete={!!readOnly}
{...rest}
/>
</div>
);
}
} }
Upload.propTypes = { Upload.propTypes = {
multiple: PropTypes.bool, // 是否支持多选 multiple: PropTypes.bool, // 是否支持多选
accept: PropTypes.string, // 上传格式限制 accept: PropTypes.string, // 上传格式限制
length: PropTypes.number, // 最大支持上传张数 length: PropTypes.number, // 最大支持上传张数
handleSubmit:PropTypes.func.isRequired, // 上传函数 handleSubmit: PropTypes.func.isRequired, // 上传函数
rest:PropTypes.object, rest: PropTypes.object,
defaultFiles:PropTypes.array, // 初始值 defaultFiles: PropTypes.array, // 初始值
readOnly:PropTypes.bool, readOnly: PropTypes.bool,
labelId:PropTypes.any // 组件id 标识 labelId: PropTypes.any // 组件id 标识
} }
Upload.defaultProps = { Upload.defaultProps = {
multiple: true, // 是否支持多选 multiple: true, // 是否支持多选
accept: 'image/*', // 上传格式限制 accept: 'image/*', // 上传格式限制
length: 10, // 最大支持上传张数 length: 10, // 最大支持上传张数
defaultFiles:[], defaultFiles: [],
readOnly:false, readOnly: false,
labelId:'' labelId: ''
} }
export default Upload; export default Upload;
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论