页面部分:javascript
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- </head>
- <body>
- <div>
- <input type="file" name="upfile" id="upfile" onchange="imgPreObj.changeFiles(this)"/>
- <div id="preview"><img src="" id="imgPre"></div>
- </div>
- </body>
- </html>
javascript代码:html
- /**
- * @title 兼容多浏览器的图片上传预览
- * @support IE6+,Firefox,Opera,Chrome
- * @author gaorunqiao / goen88@163.com
- * @version g.f.i.p0.0.0.02
- * @date 2012/08/31
- */
- //图片上传预览
- function FILE_IMG_PREVIEW(imgID){
- this.fileObj = {}; //input file对象
- this.imgID = imgID; //输出图片对象ID
- this.formatFilter = ".jpg;.png;.gif;.bmp;";
- }
- //文件选取完成回调
- FILE_IMG_PREVIEW.prototype.changeFiles = function(obj){
- this.fileObj = obj;
- var oImgID = this.imgID; //输出图片ID
- if(this.checkFormat()==false) return; //文件格式检测
- if(typeof FileReader != 'undefined'){ //支持html5读取文件URL
- var files = this.fileObj.files;
- if(files.length>0){
- var reader = new FileReader();
- reader.onloadend = function(e) {
- document.getElementById(oImgID).src= this.result;
- }
- reader.readAsDataURL(files[0]);
- }
- }else{
- document.getElementById(oImgID).src = this.getPath();
- }
- }
- //获取本地文件路径
- FILE_IMG_PREVIEW.prototype.getPath = function(){
- if (this.fileObj) {
- //取得IE下本地图片路径
- if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
- this.fileObj.select();
- this.fileObj.blur();
- // IE下取得图片的本地路径
- return document.selection.createRange().text;
- }
- //firefox
- else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
- if (this.fileObj.files) {
- // Firefox下取得的是图片的数据
- return this.fileObj.files.item(0).getAsDataURL();
- }
- return this.fileObj.value;
- }
- return this.fileObj.value;
- }else{
- return '';
- }
- }
- //检测上传文件的格式
- FILE_IMG_PREVIEW.prototype.checkFormat = function(){
- var upfile = this.fileObj.value;
- var format = upfile.substr(upfile.lastIndexOf('.')).toLowerCase();
- if(this.formatFilter.indexOf(format)!=-1){
- return true;
- }else{
- alert('错误:文件格式不正确,只支持'+this.formatFilter);
- return false;
- }
- }