本文欢迎转载,转载请注明出处,谢谢! http://blog.csdn.net/colton_null 作者:喝酒不骑马 Colton_Null from CSDN
效果
先看效果图
思路
准备一个<input type="file" style="display: none">
标签,并设置成隐藏。
再用自定义的button去触发input的点击事件即可。
代码
html:
<table>
<tr>
<td colspan="2" align="center">上传司机照片</td>
</tr>
<tr>
<td colspan="2" align="center">
<img src="../../pic/150x150.png" style="width:150px;height: 150px" id="img_driver">
</td>
</tr>
<tr>
<td align="center">
<button type="button" class="btn btn-block btn-primary btn-xs" onclick="driverUpload();"><i class="fa fa-cloud-upload"></i> 上传</button>
</td>
<td align="center">
<button type="button" class="btn btn-block btn-primary btn-xs"><i class="fa fa-trash"></i> 删除</button>
</td>
</tr>
</table>
<input type="file" id="input_upload_driver" style="display: none" accept="image/jpg, image/png, image/jpeg" onChange="preview(this,'img_driver');">
js:
/**
* 文件上传
*/
function driverUpload() {
$('#input_upload_driver').click(); // 模拟文件上传按钮点击操作
}
/**
* 缩略图预览
* @param file
* @param container
*/
var preview = function(file, container){
//缩略图类定义
var Picture = function(file, container){
var height = 0,
width = 0,
ext = '',
size = 0,
name = '',
path = '';
var self = this;
if(file){
name = file.value;
if(window.navigator.userAgent.indexOf("MSIE")>=1){
file.select();
path = document.selection.createRange().text;
}else {
if(file.files){
// path = file.files.item(0).getAsDataURL(); // firefox7.0之后该方法弃用了,用下面那个
path = window.URL.createObjectURL(file.files[0]);
}else{
path = file.value;
}
}
}else{
throw '无效的文件';
}
ext = name.substr(name.lastIndexOf("."), name.length);
if(container.tagName.toLowerCase() != 'img'){
throw '不是一个有效的图片容器';
container.visibility = 'hidden';
}
container.src = path;
container.alt = name;
container.style.visibility = 'visible';
height = container.height;
width = container.width;
size = container.fileSize;
this.get = function(name){
return self[name];
};
this.isValid = function(){
if(allowExt.indexOf(self.ext) !== -1){
throw '不允许上传该文件类型';
return false;
}
}
};
try{
var pic = new Picture(file, document.getElementById('' + container));
}catch(e){
alert(e);
}
};
注意:
path = file.files.item(0).getAsDataURL();
网上很多资料有关图片路径获取的代码,都是getAsDataURL()
。实际上这个方法在firefox 7.0和chrome 13+之后已经被弃用了。
替代方法为window.URL.createObjectURL(file.files[0]);