一、使用input标签
HTML:
<div className="upload_view_item">
<label>
<div className="hideInput">
<input type="file"
accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
onChange={(file)=> {
functions.mockUpload(file);
}
hidden
/>
<div className="add">+</div>
<div className="tips">
<p>最多5张</p>
<p>每张5M以内</p>
</div>
</div>
</label>
</div>
CSS:
.upload_view_item {
width: 2.6rem;
height: 2.6rem;
margin-bottom: .5rem;
position: relative;
.hideInput {
width: 100%;
height: 100%;
background: #E6E6E6;
border-radius: .1rem;
.add {
height: 1.3rem;
text-align: center;
font-size: 1.3rem;
font-weight: 300;
color: #999999;
}
.tips {
height: 1.3rem;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
font-family: 'MiSans';
font-weight: 400;
font-size: .32rem;
line-height: .42rem;
color: #B3B3B3;
}
}
}
JS:
import { functions} from '@/config/function';
二、压缩上传逻辑
位于:@/config/functionexport const functions = {
/**图片上传 */
mockUpload: (event) => {
const file = event.target.files && event.target.files[0];
const name = file.name;
if (file.type.includes('video')) {
Toast.show({ content: '文件格式错误,请选择图片' });
return
}
zipImg(file, 0.2, (result) => {
const arr: any = result.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = window.atob(arr[1]);
let length = bstr.length;
const u8arr = new Uint8Array(length);
while (length--) {
u8arr[length] = bstr.charCodeAt(length);
}
const data = new File([u8arr], name, { type: mime });
const formData = new FormData();
formData.append('file', data);
const param = formData;
const headers = { headers: { 'Content-Type': 'multipart/form-data' } };
Toast.show({ icon: 'loading', content: '上传中…', duration: 0 });
upload(param, headers)
.then(async (res) => {
const { code, codeMsg, filePath } = res.data;
if (code === 200 && codeMsg === 'SUCCESS') {
Toast.show({ content: '上传成功' });
} else {
Toast.show({ content: '上传失败' });
}
})
.catch(() => {
Toast.show({ content: '服务异常,请联系客服' })
})
})
}
}
zipImg压缩方法:const zipImg = (url: any, rate: any, cb: (arg0: string) => void) => {
// 处理缩放
const _img = new Image();
_img.src = URL.createObjectURL(url);
_img.onload = () => {
const _canvas: any = document.createElement('canvas');
_canvas.width = _img.width;
_canvas.height = _img.height;
_canvas.getContext('2d').drawImage(_img, 0, 0);
const result = _canvas.toDataURL('image/jpeg', rate);
if (cb) cb(result);
};
};
您已经阅读00:00:00欢迎留言评论,喜欢的话就为作者点个赞或者赏颗糖吧! 分享
发表评论(不少于3个字符) 取消回复