Input
<input type="file" /> 标签
type= "file" 时
定义支持上传的文件类型:设置 accept
accept="image/bmp,image/jpeg,image/jpg,image/png"
效果:
点击选择文件,弹出选择文件的弹框,被允许的类型可以选择,
未被accept的类型是灰色,不可选。
坑: input 为file cursor: pointer 无效 ?
![](https://i-blog.csdnimg.cn/blog_migrate/4c83d516a7a29cfef99f154c249df9d3.png)
上传文件样式太丑。。
整容样式如下。
.
button {
position: relative;
display: inline-block;
width:100px;
height: 36px;
line-height: 36px;
.
input {
position: absolute;
top: 0;
left: -50px;
display: inline-block;
height: 100%;
line-height: 36px;
overflow: hidden;
opacity: 0;
z-index: 100;
cursor: pointer;
.img-pre { // 支持一个或多个图片预览
display: inline-block;
position: absolute;
left: 125px;
top: -3px;
white-space: nowrap;
& > img {
display: inline-block;
height: 40px;
width: 40px;
margin: 0 5px;
}
}
}
}
multiple
添加这个属性可以以此选择多个,默认是展示选中的个数,一次选中多个,不是多次不能添加。
onchange
事件返回 bool 值,返回值为true时文件选择成功,返回值为 false 文件选择失败
onchange事件默认参数 event 可以获取 e.target.files 获取已选择的文件列表对象数组,单项包含文件属性值如下:
主要文件属性如下:
lastModified: 1565074500694
lastModifiedDate: Tue Aug 06 2019 14:55:00 GMT+0800 (中国标准时间) {}
name: "RNGuestGuide_bitmap.png"
size: 152720 (单位是 Byte 字节 Math.round(size / 1000) Kb )
type: "image/png"
图片上款后最好有预览功能,继续优化。
样式需要调整,上面已添加
预览思路: 获取文件file -> URL.createObjectURL(file) -> 获取图片 url地址数组 -> 创建img标签添加url,添加到dom -> 完成预览。
方法优化思路:支持多图预览,支持文件个数可变,支持统一调用。
代码如下:
参数说明: fes: input file对象, fileLength: 图片个数限制值。
fileCheck (fes, fileLength) {
let files = Array.from(fes);
let fileCount = files && files.length;
if (fileCount <= fileLength) {
if (files.some(v => (Math.round(v.size / 1000) > 500))) {
Toast.show({ info: '图片大小最大支持500Kb', duration: 2000});
return false;
} else {
let urls = [];
files.forEach((v) => {
urls.push(URL.createObjectURL(v));
});
return urls;
}
} else {
Toast.show({ info: '图片超过个数', duration: 2000});
return false;
}
}
于是可以得到一个上传一组图片的处理方案。