浏览器 本地预览图片 window.url.createobjecturl

第一种方式
  1. <script type="text/javascript">
  2. function setImagePreview() {
  3. var docObj = document.getElementById("ctl00_ContentMain_file_head");
  4. var fileName = docObj.value;
  5. if (!fileName.match(/.jpg|.gif|.png|.bmp/i)) {
  6. alert('您上传的图片格式不正确,请重新选择!');
  7. return false;
  8. }
  9. var imgObjPreview = document.getElementById("preview");
  10. if (docObj.files && docObj.files[0]) {
  11. //火狐下,直接设img属性
  12. imgObjPreview.style.display = 'block';
  13. imgObjPreview.style.width = '63px';
  14. imgObjPreview.style.height = '63px';
  15. //imgObjPreview.src = docObj.files[0].getAsDataURL();
  16. if (window.navigator.userAgent.indexOf("Chrome") >= 1 || window.navigator.userAgent.indexOf("Safari") >= 1) {
  17. imgObjPreview.src = window.webkitURL.createObjectURL(docObj.files[0]);
  18. }
  19. else {
  20. imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
  21. }
  22. } else {
  23. //IE下,使用滤镜
  24. docObj.select();
  25. docObj.blur();
  26. var imgSrc = document.selection.createRange().text;
  27. var localImagId = document.getElementById("localImag");
  28. //必须设置初始大小
  29. localImagId.style.width = "63px";
  30. localImagId.style.height = "63px";
  31. //图片异常的捕捉,防止用户修改后缀来伪造图片
  32. try {
  33. localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
  34. localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
  35. } catch (e) {
  36. alert("您上传的图片格式不正确,请重新选择!");
  37. return false;
  38. }
  39. imgObjPreview.style.display = 'none';
  40. document.selection.empty();
  41. }
  42. return true;
  43. }
  44. </script>


<div id="localImag"><img id="preview" width="-1" height="-1" style="display:none" /></div> 
<asp:FileUpload ID="file_head" runat="server" onchange="javascript:setImagePreview();" /> 


第二种方式


  1. function setImagePreview(a,b) {
  2. var url ='';
  3. if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
  4. url = document.getElementById(a).value;
  5. } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
  6. url = window.URL.createObjectURL(document.getElementById(a).files.item(0));
  7. } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
  8. url = window.URL.createObjectURL(document.getElementById(a).files.item(0));
  9. }
  10. var imgPre = document.getElementById(b);
  11. imgPre.src = url;
  12. }

a = fileid
b=imgid



posted on 2017-03-22 14:38  signheart  阅读(2901)  评论(0编辑  收藏  举报

导航