SoFunction
Updated on 2025-03-01

Preview function before uploading js image (compatible with all browsers)

A preview code found on the Internet to preview the file before uploading, reproduced from JavaScript images before uploading (compatible with all browsers)

<!DOCTYPE html>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
 <style type="text/css">
 #preview,
 .img,
 img {
  width: 200px;
  height: 200px;
 }
 
 #preview {
  border: 1px solid #000;
 }
 </style>
</head>

<body>
 <div ></div>
 <input type="file" onchange="preview(this)" />
 <script type="text/javascript">
 function preview(file) {
  var prevDiv = ('preview');
  if ( && [0]) {
   var reader = new FileReader();
    = function(evt) {
     = '<img src="' +  + '" />';
   }
   ([0]);
  } else {
    = '<div class="img" style="filter:progid:(sizingMethod=scale,src=\'' +  + '\'"></div>';
  }
 }
 </script>
</body>
</html>

Key points of implementation

● For Chrome, Firefox, and IE10, use FileReader to implement it.
● For IE6~9, use filter:progid: to achieve it.
I tested IE8+ without any problems. However, the file path splitting line was removed by the browser in IE7 and it could not be displayed.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.