通过<input />标签,给它指定type类型为file,可提供文件上传;
accept:可选择上传类型,如:只要传图片,且不限制图片格式,为image/*;
multiple:规定是否可以选择多个文件;
规定只可上传图片,且可以选择多个文件
1
|
<
input
type
=
"file"
accept
=
"image/*"
multiple
=
"multiple"
/>
|
当然,直接一个input type=file 只能选择上传的文件/资源,如果我们需要在选择图片之后,在当前页面实现预览效果,那么我们可以如下方式来实现
HTML代码
1
2
3
4
5
6
7
8
|
<
body
>
<
div
id
=
"box"
>
<
img
id
=
"imgshow"
src
=
""
alt
=
""
/>
</
div
>
<
div
id
=
"pox"
>
<
input
id
=
"filed"
type
=
"file"
accept
=
"image/*"
/>
</
div
>
</
body
>
|
css样式文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<
style
>
#box{
width: 300px;
height: 300px;
border: 2px solid #858585;
}
#imgshow{
width: 100%;
height: 100%;
}
#pox{
width: 70px;
height: 24px;
overflow: hidden;
}
</
style
>
|
JS代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<
script
>
//在input file内容改变的时候触发事件
$('#filed').change(function(){
//获取input file的files文件数组;
//$('#filed')获取的是jQuery对象,.get(0)转为原生对象;
//这边默认只能选一个,但是存放形式仍然是数组,所以取第一个元素使用[0];
var file = $('#filed').get(0).files[0];
//创建用来读取此文件的对象
var reader = new FileReader();
//使用该对象读取file文件
reader.readAsDataURL(file);
//读取文件成功后执行的方法函数
reader.onload=function(e){
//读取成功后返回的一个参数e,整个的一个进度事件
console.log(e);
//选择所要显示图片的img,要赋值给img的src就是e中target下result里面
//的base64编码格式的地址
$('#imgshow').get(0).src = e.target.result;
}
})
</
script
>
|
*以上js代码中有使用到jQuery,因此要引入jQuery文件
这篇input type=file 选择图片并且实现预览效果的实例就是小编分享给大家的全部内容了,
如何去掉 input type=file 的 “未选择任何文件”标志?
并且
<style>
input[type="file"] {
color: transparent;
}
</style>
<input type="file">
可以实现
如何去掉 input type=file 的 “未选择任何文件”标志?
如何去掉 input type=file 的 “未选择任何文件”标志?