HTML添加上传图片并进行预览

news/2024/7/7 19:27:26

使用说明:新建文件,直接复制粘贴,保存文件为html 格式,在浏览器运行即可;

第一种:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><title> New Document </title></head><script src="http://i.gtimg.cn/qzone/biz/gdt/lib/jquery/jquery-2.1.4.js?max_age=31536000"></script><script>$(function(){  $('#upLoad').on('change',function(){  var filePath = $(this).val(),         //获取到input的value,里面是文件的路径  
            fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),  imgBase64 = '',      //存储图片的imgBase64  
            fileObj = document.getElementById('upLoad').files[0]; //上传文件的对象,要这样写才行,用jquery写法获取不到对象  // 检查是否是图片  if( !fileFormat.match(/.png|.jpg|.jpeg/) ) {  alert('上传错误,文件格式必须为:png/jpg/jpeg');  return;    }  // 调用函数,对图片进行压缩  
        compress(fileObj,function(imgBase64){  imgBase64 = imgBase64;    //存储转换的base64编码  
            $('#viewImg').attr('src',imgBase64); //显示预览图片  
        });  });  // 不对图片进行压缩,直接转成base64  function directTurnIntoBase64(fileObj,callback){  var r = new FileReader();  // 转成base64  
        r.onload = function(){  //变成字符串  
            imgBase64 = r.result;  console.log(imgBase64);  callback(imgBase64);  }  r.readAsDataURL(fileObj);    //转成Base64格式  
    }  // 对图片进行压缩  function compress(fileObj, callback) {   if ( typeof (FileReader) === 'undefined') {    console.log("当前浏览器内核不支持base64图标压缩");    //调用上传方式不压缩    
            directTurnIntoBase64(fileObj,callback);  } else {    try {      var reader = new FileReader();    reader.onload = function (e) {    var image = $('<img/>');    image.load(function(){    square = 700,   //定义画布的大小,也就是图片压缩之后的像素  
                        canvas = document.createElement('canvas'),   context = canvas.getContext('2d'),  imageWidth = 0,    //压缩图片的大小  
                        imageHeight = 0,   offsetX = 0,   offsetY = 0,  data = '';   canvas.width = square;    canvas.height = square;   context.clearRect(0, 0, square, square);     if (this.width > this.height) {    imageWidth = Math.round(square * this.width / this.height);    imageHeight = square;    offsetX = - Math.round((imageWidth - square) / 2);    } else {    imageHeight = Math.round(square * this.height / this.width);    imageWidth = square;    offsetY = - Math.round((imageHeight - square) / 2);    }    context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);    var data = canvas.toDataURL('image/jpeg');    //压缩完成执行回调    
                         callback(data);    });    image.attr('src', e.target.result);    };    reader.readAsDataURL(fileObj);    }catch(e){    console.log("压缩失败!");    //调用直接上传方式  不压缩   
                directTurnIntoBase64(fileObj,callback);   }    }  }  
});  </script><body>  <input type="file" id="upLoad" name="image" >  <!-- 显示上传之后的图片 -->  <div id='previewImg'>  <img src="" id='viewImg'/>  </div>  
</body> 
</html>

 第二种:

<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><title>Document</title>
</head>
<body>
<input type="file"><br>
<img src="" height="200" alt="Image preview area..." title="preview-img">
<script>var fileInput = document.querySelector('input[type=file]'),previewImg = document.querySelector('img');fileInput.addEventListener('change', function () {var file = this.files[0];var reader = new FileReader();// 监听reader对象的的onload事件,当图片加载完成时,把base64编码賦值给预览图片reader.addEventListener("load", function () {previewImg.src = reader.result;}, false);// 调用reader.readAsDataURL()方法,把图片转成base64reader.readAsDataURL(file);}, false);
</script>
</body>
</html>

  

转载于:https://www.cnblogs.com/YLQBL/p/8269581.html


http://lihuaxi.xjx100.cn/news/239167.html

相关文章

在Google Cloud Platform上持续部署Node.js

by Gautam Arora由Gautam Arora 在Google Cloud Platform上持续部署Node.js (Continuous Deployment for Node.js on the Google Cloud Platform) Google Cloud Platform (GCP) provides a host of options for Node developers to easily deploy our apps. Want a managed ho…

linux基础学习(二)

------------------------------------------------------------------------------------------------------------------------------------------------0.真机远程管理虚拟机telnet 明文传输 tcp 23ssh 加密传输 tcp 22ssh -X root172.25.0.11 //真机远程管理 ser…

linux系统下怎么使用lspci,Linux系统之lspci命令介绍

lspci&#xff0c;顾名思义&#xff0c;就是显示所有的pci设备信息。pci是一种总线&#xff0c;而通过pci总线连接的设备就是pci设备了。如今&#xff0c;我们常用的设备很多都是采用pci总线了&#xff0c;如&#xff1a;网卡、存储等。下面就简单介绍下该命令。lspci&#xff…

这是如何更好地利用JavaScript数组的方法

by pacdiv由pacdiv 这是如何更好地利用JavaScript数组的方法 (Here’s how you can make better use of JavaScript arrays) Quick read, I promise. Over the last few months, I noticed that the exact same four mistakes kept coming back through the pull requests I c…

关于javascript代码优化的8点建议

前面的话 本文将详细介绍JS编程风格的几个要点 松耦合 当修改一个组件而不需要更改其他组件时&#xff0c;就做到了松耦合 1、将JS从CSS中抽离&#xff1a;不要使用CSS表达式 //不好的做法 .box{width: expression(document.body.offsetWidth ’px)} 2、将CSS从JS中抽离&#…

CentOS7启动图形界面

1.yum groupinstall "GNOME Desktop" -y 2.systemctl get-default 3.systemctl set-default graphical.target 4.systemctl get-default 5.reboot

观察内核linux行为,Linux 学习:基于proc观察Linux行为

内容简介本篇博文的主要内容是通过/proc文件&#xff0c;对Linux系统管理有一个初步的认识。在Linux中&#xff0c;proc文件系统提供了一套在用户态检查内核状态和系统特征的机制。proc文件系统将进程的地址空间、系统的硬件信息、系统相关机制(中断、I/O)等内容全部设置为虚拟…

Vbox共享文件夹不显示了

博主之前装的虚拟机没啥问题&#xff0c;按部就班&#xff0c;打开“我的电脑”可以看到主机上的共享文件夹&#xff0c;最近重装了一波&#xff0c;各种问题就来了&#xff0c;包括共享文件夹设置好后&#xff0c;看不见了。 介绍比较麻烦的方案&#xff0c;就是打开“我的电脑…