一、html部分
<!-- accept限制上传类型 -->
<input type="file" name="" id="upload" accept="image/*">
<!-- -->
<img src="" alt="" id="preview">
二、js部分
2.1获取预览链接以及宽高
这里是通过URL.createObjectURL()获取预览链接
/**
* 实现图片预览
* file => 文件对象
*/
function previewFile(file) {
// 获取预览链接
const url = window.URL.createObjectURL(file);
// 创建异步对象将其return出去
return new Promise((res, rej) => {
// 创建Image对象
const element = new Image();
// 绑定src
element.src = url
// 当图片加载完成时触发 onload
element.onload = () => {
// 获取图片的宽高
const w = Math.floor(element.width),
h = Math.floor(element.height);
// 返回获取到的值
res({
code: 1,
data: {
wh: [w, h],
}
})
}
// 当图片渲染错误时触发 onerror
element.onerror = () => {