需求:在点击上传图标的时候会在前面的input框中显示出文件名,然后点击后面的查看按钮就可以预览选择的这张图片了,要求不能刷新页面
1.一开始的时候打算用ajax上传,后来发现多张图片一同上传的时候会出现问题,ajax上传图片的原理是当你选中一张图片的时候会使用js在这个type为file的input的框外面包上一个form表单然后通过ajaxSubmit自动提交到PHP文件,之后通过PHP文件进行上传,最后返回一个上传到服务器的图片路径,点击查看的时候就可以获取到这个图片,实际上这个时候图片已经上传到服务器了。但这个需求是多张图片,这么做会出现很大的问题。
2.之后在网上查到了使用js实时预览本地选中的图片,这个和ajax上传的不同就是,在选择完图片文件之后并不会上传到服务器,而是直接调取本机图片的路径预览。下面就是用这种方法实现最终效果的例子。
方法:
<input type=file name=photo_file[] class=ata_pt οnchange=previewImage(this)/> <input type=hidden class=imageurl />
然后在下面加一个获取它的本地图片路径的隐藏形式的input的框
//图片上传预览 IE是用了滤镜。 function previewImage(file) { if (file.files && file.files[0]) { var reader = new FileReader(); reader.onload = function(evt){ $(file).next().val(evt.target.result); } reader.readAsDataURL(file.files[0]); } else //兼容IE { var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaimageLoader(sizingMethod=scale,src='; file.select(); var src = document.selection.createrange().text; //p.innerHTML = '<img id=imghead>'; //var img = document.getElementById('imghead'); //img.filters.item('DXImageTransform.Microsoft.AlphaimageLoader').src = src; $(this).next().val(src); //var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight); //status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height); //p.innerHTML = <p id=phead style='width:+rect.width+px;height:+rect.height+px;margin-top:+rect.top+px;+sFilter+src+\'></p>; } } function clacImgZoomParam( maxWidth, maxHeight, width, height ){ var param = {top:0, left:0, width:width, height:height}; if( width>maxWidth || height>maxHeight ) { rateWidth = width / maxWidth; rateHeight = height / maxHeight; if( rateWidth > rateHeight ) { param.width = maxWidth; param.height = Math.round(height / rateWidth); }else { param.width = Math.round(width / rateHeight); param.height = maxHeight; } } param.left = Math.round((maxWidth - param.width) / 2); param.top = Math.round((maxHeight - param.height) / 2); return param; }
可以看到在选择图片的时候调用了previewImage()方法,使用这个方法获取了本机图片的地址传入到class为imageurl的input框中。
之后是创建一个查看按钮,我是在
<input type=hidden class=imageurl />
下面直接加了一个按钮,当点击这个按钮的时候获取$(this).prev().val(),然后传给想要显示图片的p中的img里,这样图片就显示出来了
<p><img src= id=preview></p>
经过测试这个方法可以满足firefox,chrome,ie10以上,基本上已经够用了吧。
压了几天得问题没想到就这么解决了,效率不高,积累经验!积累经验!积累经验!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。