欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

原生javascript上传图片带进度条【实例分享】

程序员文章站 2022-06-11 19:26:54
javascript代码: ; (function(w) { var error = "上传控件不支持您的浏览器!"; // 构造函数 func...

javascript代码:

 ;
 (function(w) {
 var error = "上传控件不支持您的浏览器!";
 // 构造函数
 function uploadimg(option) {
  $u = this;
  $u.option = option;
  $u.init($u.option);
 }
 uploadimg.prototype = {
  //初始化
  init: function() {
  var $u = this;  
  //template
  $u.adduploader =
   '<form enctype="multipart/form-data">' +
   '<label style="display:block;width:100%;cursor:pointer;height:100%;position: absolute;">' +
   '<input class="kechenfengmian" type="file" capture="camera" name="file"/>' +
   '</label>' +
   '</form> ' +
   '<img src="" width="280" height="160" />' +
   '<div class="upload-progress"><span class="upload-son">等待中……</span></div>' +
   '<div class="mask-div">' +
   '<div class="mask-show"></div>' +
   '<div class="button-div">' +
   '<span class="upload-btn"></span>' +
   '<span class="deleteimg-btn"></span></div>' +
   '</div>';
  $u.wrap = $($u.option.el);
  $u._creatfrom();
  $u.eventchange($u.wrap.childnodes);
  },
  //生成form模板
  _creatfrom: function() {
  this.wrap.innerhtml = $u.adduploader;
  },
  _removefrom: function() {
  this.wrap.innerhtml = "";
  },
  //事件触发
  /*
  *对于onchange事件若值没有发生改变的话
  *此事件就会失效所以在这里打算将dom移除
  *直接初始化所有方法和事件
  *
  */
 /**
  *@method (eventchange) 
  *@param {childarr} 参数为数组集合  
  */
  eventchange: function(childarr) {
  var $u = this;
  //提交form表单
  addevent(childarr[0], 'change', function(e) { 
  //保存当前this对象 
   var thisform = this;    
   if (!thisform['file'].files.length == 0) {
   $u._removefrom();
   $u.init();
   testwidthheight(e,function(issize){
   if(!issize){ 
    alert("上传的尺寸为:长为"+$u.option.max_width +"宽为"+$u.option.max_height); 
    return false; 
    }
    childarr[2].setattribute('src', "");
    childarr[3].style.display = 'block';
    $u.wrap.style.background = "#f3f3f3";
    //发送post请求
    $u.ajaxpost(thisform, $u.option.url, function(result) {
    //post成功
    var data = json.parse(result);
    $u.maskevent(childarr);
    childarr[2].setattribute('src', data.url);
    childarr[3].style.display = 'none';
    }, function(error) {
     //post 失败 
     console.log(error);
    }, childarr);
   });
   } else {  
   alert("上传个数不能为0");  
   return false;
   }
  });
  /**
  *@method (testwidthheight) 获取上传尺寸大小
  *@param {e} 事件对象
  *@param {callback} 回调函数  
  */
  function testwidthheight(e,callback) {
  var issize;
  var forms = e.target;
  var reader = new filereader();
  reader.onload = function () { 
   var dataurl = reader.result; 
   var image = new image();
   image.onload=function(){ 
    var width = image.width;
    var height = image.height;
    issize = width <= $u.option.max_width && height <= $u.option.max_height; 
    if(typeof callback == 'function') {
    callback(issize);
    }   
   };  
   image.src = dataurl;
  }; 
  reader.readasdataurl(forms.files[0]); 
  return issize; 
  }
  },
  //遮罩层上的是事件
  maskevent: function(childarr) {
  $u = this;
  var addbtn = childarr[4].childnodes[1].childnodes[0];
  var delebtn = childarr[4].childnodes[1].childnodes[1];
  //当鼠标滑过
  addevent($u.wrap, "mouseover", function() {
   if (childarr[2].getattribute('src')) {
   childarr[4].style.top = 0;
   }
  });
  //当鼠标离开
  addevent($u.wrap, "mouseout", function() {
   childarr[4].style.top = -300 + 'px';
  });
  //修改
  addevent(addbtn, 'click', function() {
   childarr[0][0].click();
  });
  //删除
  addevent(delebtn, 'click', function() {
   $u.wrap.style.backgroundimage = "url(add-bg-upload1.jpg)";
   childarr[2].setattribute('src', "");
  });
  },
 /**
 *@method (ajaxpost) 上传方法
 *@param {fm} 当前form表单
 *@param {url} url地址 
 *@param {fnsuc} 成功回调 
 *@param {fnerr} 失败回调 
 *@param {childarr} 节点集合  
 */
  ajaxpost: function(fm, url, fnsuc, fnerr, childarr) {
  var $u = this;
  //进度条
  var progress = childarr[3].childnodes[0];
  if (window.xmlhttprequest) {
   var xhr = new xmlhttprequest();
  } else {
   var xhr = new activexobject("microsoft.xmlhttp");
  }
  //data数据 
  var data = new formdata(fm);
  xhr.onreadystatechange = function() {
   if (xhr.readystate == 4) {
   //成功回调
   if (xhr.status == 200) {
    fnsuc(xhr.responsetext);
   } else {
    if (fnerr) {
    fnerr(xhr.status);
    }
   }
   }
  };
  //监听上传进度  
  addevent(xhr.upload, "progress", uploadprogress);
  //post后台
  xhr.open('post', url);
  //发送数据
  xhr.send(data);
  //上传进度
  function uploadprogress(evt) {
   var loaded = evt.loaded; //已上传的文件大小
   var alltotal = evt.total; //总大小
   var per = math.floor((loaded / alltotal) * 100) + '%';
   progress.innerhtml = per;
   progress.style.width = per;
  }
  },
 };
 //获取元素
 function $(selectors) {
  return document.queryselector(selectors);
 }
 //事件监听
 function addevent(el, type, fn) {
  if (el.addeventlistener) {
  el.addeventlistener(type, fn, false);
  } else if (el.attachevent) {
  el.attachevent('on' + type, function() {
   fn.call(el);
  });
  } else {
  throw new error('not supported or dom not loaded');
  }
 }
 //判断浏览器是否存在file属性
 if (window.file && window.filelist) {
  window.uploadimg = uploadimg;
 } else {
 alert(error);
  return false;
 }
 })(window);

php代码:

<?php
$file=$_files['file'];
foreach ($file as $key => $value) {
 $$key=$value;
}
$path='upload/'.time().strtolower(strstr($name, '.')); //修改上传文件的名称,strstr($name, '.')是获取后缀名
move_uploaded_file($tmp_name,$path);
$path=strstr($path,$path[0]); //图片的存储地址
$arr=array( 
 "url"=>$path
);
$json=json_encode($arr); //json
echo $json;
?>

css代码:

 .couser-img-upload {
  width:280px;
  height:160px;  
  cursor:pointer;
  position: relative;
  overflow: hidden;
  background:url(add-bg-upload1.jpg);  
 }
 .couser-img-upload:hover{
  border: 2px solid #00caac;
  background:url(add-bg-upload.jpg);
 }
 .kechenfengmian {
  display:none;
 }
 .upload-progress{
  display: none;
  width: 90%;
  position: absolute;  
  overflow: hidden;
  border:1px solid #00caac;
  border-radius: 8px;
  top: 50%;
  margin-top: -7.5px;
  left: 50%;
  padding: 2px;
  margin-left:-46%;
  font-size: 12px;
 }
 .upload-progress .upload-son{
  display: inline-block;
  background: #00caac;
  border-radius: 8px;
  text-align: center;
  color: #fff;
 }
 .mask-div{
  position: absolute;
  top: -300px;
  width: 100%;
  height: 100%;
 }
 .mask-div .mask-show{
  position: absolute;
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.5;
 }
 .mask-div .button-div{
  width: 140px;
  height: 50px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -70px;
  margin-top: -25px;
 }
 .mask-div .button-div span{
  display: block;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  background:url(tianjiashanchu.png) no-repeat;
 }
 .mask-div .button-div span.upload-btn{  
  background-position: 0px 0px;
  float: left;
 }
 .mask-div .button-div span.deleteimg-btn{
  background:url(tianjiashanchu.png) no-repeat;
  background-position: -50px 0px ;
  float: right;
 }
 .mask-div .button-div span.upload-btn:hover{
  background-position: 0px -50px ;
 }
 .mask-div .button-div span.deleteimg-btn:hover{
  background-position: -50px -50px ;
 }

html代码:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title></title>
  <script type="text/javascript" src="uploadimg.js"></script>
</head>
<body>
<div class="couser-img-upload"></div> 
<script type="text/javascript"> 
  new uploadimg({
    el:".couser-img-upload",
    url:'./upload.php',
    max_width:280,
    max_height:160
  });
</script>
</body>
</html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!