如何在上传前预览图像

如何在上传前预览图像

本文介绍了如何在上传前预览图像,获取文件大小,图像高度和宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

> HTML5和



以下是未注释的工作代码片段示例

  window.URL = window.URL || window.webkitURL; var elBrowse = document.getElementById(browse),elPreview = document.getElementById(preview),useBlob = false&& window.URL; //设置为`true`来使用Blob而不是Data-URL函数readImage(file){var reader = new FileReader(); reader.addEventListener(load,function(){var image = new Image(); image.addEventListener(load,function(){var imageInfo = file.name +''+ image.width +'×'+ image.height +''+ file.type +''+ Math.round(file.size / 1024)+'KB'; //显示图片和信息elPreview.appendChild(this); elPreview.insertAdjacentHTML(beforeend, imageInfo +'< br>'); if(useBlob){//释放一些内存window.URL.revokeObjectURL(image.src);}}); image.src = useBlob?window.URL.createObjectURL(file): reader.result;}); reader.readAsDataURL(文件); } if(files){errors + =文件上传不支持您的浏览器。;} if(files& amp; amp; ;& files [0]){for(var i = 0; i< files.length; i ++){var file = files [i]; if((/\.(png|jpeg|jpg|gif )$ /i).test(file.name)){readImage(file);} else {errors + = file.name +Unsupported Image extension \\\
;}}} //处理错误if(errors){alert(错误);}});
#preview img {height :100px;} < input id =browse type =filemultiple />< div id =preview>< / div>






在图像预览区使用输入和div

 < input id =browsetype =filemultiple> 
< div id =preview>< / div>

让我们也使用CSS来保持合成高度:

  #preview img {height:100px; } 

JavaScript

  window.URL = window.URL || window.webkitURL; 
var elBrowse = document.getElementById(browse),
elPreview = document.getElementById(preview),
useBlob = false&& window.URL; //设置为true以使用Blob而不是Data-URL

// 2.
函数readImage(文件){

//创建一个新的FileReader实例
// https://developer.mozilla.org/en/docs/Web/API/FileReader
var reader = new FileReader();

//一旦成功读取文件:
reader.addEventListener(load,function(){

//此时`reader.result `已经包含Base64 Data-URL
//我们可以使用
//`elPreview.insertAdjacentHTML(beforeend,< img src ='+ reader)立即显示图像。结果+'>);`
//但是我们想得到图像的宽度和高度px值!
//由于文件对象不包含图像的大小
//我们需要创建一个新图像并指定它的src,所以当
//图像被加载时,我们可以计算它的宽度和高度:
var image = new Image();
image.addEventListener(load,function(){

//连接我们的HTML图像信息
var imageInfo = file.name +''+ //获取`name的值`from`file` Obj
image.width +'×'+ //但是从我们的`image`获取宽度
image.height +''+
file.type +''+
Math.round(file.size / 1024)+'KB';

//最后将我们创建的图像和HTML信息字符串附加到我们的`#preview`
elPreview.appendChild(this);
elPreview.insertAdjacentHTML(beforeend,imageInfo +'< br>');

//如果我们将变量`useBlob`设置为true:
//(数据URL最终会变得非常大
//`src =data:image / png; base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAA ........... etc`
// Blob通常更快,图像src将保存更短的blob名称
// src =blob: http%3A // example.com / 2a303acf-c34c-4d0a-85d4-2136eef7d723
if(useBlob){
//释放一些内存以获得最佳性能
window.URL.revokeObjectURL( image.src);
}
});

image.src = useBlob?window.URL.createObjectURL(file):reader.result;

$)

// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
reader.readAsDataURL(file);
}

// 1.
//一旦用户选择了所有要上传
//的文件,它将触发`#browse上的`change'事件`input
elBrowse.addEventListener(change,function(){

//让我们存储FileList数组到一个变量:
// https://developer.mozilla.org/en-US/docs/Web/API/FileList
var files = this.files;
//让我们创建一个空的`errors`字符串来收集最终的错误:
var errors =;

if(!files){
errors + =您的浏览器不支持文件上传。;
}

//检查是否支持`files`(FileList),如果包含至少一个文件:
if(files&& files [0]){

//迭代FileList数组中的每个File对象
for(var i = 0; i< files.length; i ++){

//让我们来引用到当前文件作为`文件`变量
// https://developer.mozilla.org/en-US/docs/Web/API/File
var file = files [i];

//测试`file.name`是否有效的图像扩展名:
//(管道`|`分隔更多图像扩展名)
//正则表达式也可以表示如下:/(如果((/\.(png|jpeg|jpg|gif)$/i).test(file.name))/ /(.gp)$ / $
){
//成功!这是一个图像!
//将我们的图像`file`发送到`readImage`函数!
readImage(file);
} else {
errors + = file.name +不支持的图片扩展名\ n;



$ b //通知用户有任何错误(即:尝试上传.txt文件)
if(errors){
警报(错误);
}

});


How can I get the file size, image height and width before upload to my website, with jQuery or JavaScript?

解决方案

HTML5 and the File API

Here's the uncommented working code snippet example:

window.URL    = window.URL || window.webkitURL;
var elBrowse  = document.getElementById("browse"),
    elPreview = document.getElementById("preview"),
    useBlob   = false && window.URL; // set to `true` to use Blob instead of Data-URL

function readImage (file) {
  var reader = new FileReader();

  reader.addEventListener("load", function () {
    var image  = new Image();

    image.addEventListener("load", function () {
      var imageInfo = file.name +' '+
          image.width +'×'+
          image.height +' '+
          file.type +' '+
          Math.round(file.size/1024) +'KB';

      // Show image and info
      elPreview.appendChild( this );
      elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');

      if (useBlob) {
        // Free some memory
        window.URL.revokeObjectURL(image.src);
      }
    });
    image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
  });

  reader.readAsDataURL(file);
}


elBrowse.addEventListener("change", function() {

  var files = this.files, errors = "";

  if (!files) {
    errors += "File upload not supported by your browser.";
  }

  if (files && files[0]) {

    for(var i=0; i<files.length; i++) {
      var file = files[i];

      if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
        readImage( file );
      } else {
        errors += file.name +" Unsupported Image extension\n";
      }

    }
  }

  // Handle errors
  if (errors) {
    alert(errors);
  }

});
#preview img{height:100px;}
<input id="browse" type="file"  multiple />
<div id="preview"></div>


Using an input and a div for the images preview area

<input id="browse" type="file" multiple>
<div id="preview"></div>

let's also use a CSS to keep the resulting images a reasonable height:

#preview img{ height:100px; }

JavaScript:

window.URL    = window.URL || window.webkitURL;
var elBrowse  = document.getElementById("browse"),
    elPreview = document.getElementById("preview"),
    useBlob   = false && window.URL; // Set to `true` to use Blob instead of Data-URL

// 2.
function readImage (file) {

  // Create a new FileReader instance
  // https://developer.mozilla.org/en/docs/Web/API/FileReader
  var reader = new FileReader();

  // Once a file is successfully readed:
  reader.addEventListener("load", function () {

    // At this point `reader.result` contains already the Base64 Data-URL
    // and we've could immediately show an image using
    // `elPreview.insertAdjacentHTML("beforeend", "<img src='"+ reader.result +"'>");`
    // But we want to get that image's width and height px values!
    // Since the File Object does not hold the size of an image
    // we need to create a new image and assign it's src, so when
    // the image is loaded we can calculate it's width and height:
    var image  = new Image();
    image.addEventListener("load", function () {

      // Concatenate our HTML image info
      var imageInfo = file.name    +' '+ // get the value of `name` from the `file` Obj
          image.width  +'×'+ // But get the width from our `image`
          image.height +' '+
          file.type    +' '+
          Math.round(file.size/1024) +'KB';

      // Finally append our created image and the HTML info string to our `#preview`
      elPreview.appendChild( this );
      elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');

      // If we set the variable `useBlob` to true:
      // (Data-URLs can end up being really large
      // `src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAA...........etc`
      // Blobs are usually faster and the image src will hold a shorter blob name
      // src="blob:http%3A//example.com/2a303acf-c34c-4d0a-85d4-2136eef7d723"
      if (useBlob) {
        // Free some memory for optimal performance
        window.URL.revokeObjectURL(image.src);
      }
    });

    image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;

  });

  // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
  reader.readAsDataURL(file);
}

// 1.
// Once the user selects all the files to upload
// that will trigger a `change` event on the `#browse` input
elBrowse.addEventListener("change", function() {

  // Let's store the FileList Array into a variable:
  // https://developer.mozilla.org/en-US/docs/Web/API/FileList
  var files  = this.files;
  // Let's create an empty `errors` String to collect eventual errors into:
  var errors = "";

  if (!files) {
    errors += "File upload not supported by your browser.";
  }

  // Check for `files` (FileList) support and if contains at least one file:
  if (files && files[0]) {

    // Iterate over every File object in the FileList array
    for(var i=0; i<files.length; i++) {

      // Let's refer to the current File as a `file` variable
      // https://developer.mozilla.org/en-US/docs/Web/API/File
      var file = files[i];

      // Test the `file.name` for a valid image extension:
      // (pipe `|` delimit more image extensions)
      // The regex can also be expressed like: /\.(png|jpe?g|gif)$/i
      if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
        // SUCCESS! It's an image!
        // Send our image `file` to our `readImage` function!
        readImage( file );
      } else {
        errors += file.name +" Unsupported Image extension\n";
      }
    }
  }

  // Notify the user for any errors (i.e: try uploading a .txt file)
  if (errors) {
    alert(errors);
  }

});

JSFIDDLE

这篇关于如何在上传前预览图像,获取文件大小,图像高度和宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 20:44