前端上传图片2

我心飞翔 分类:javascript

1,前端完整代码

<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
#new .txt{display: block;border-radius: 5px;  width: 80%; height: 80px; line-height: 80px; margin: 20px; text-indent: 20px; border: 1px solid #cccccc;position: center;}
#new .txt2{ block;border-radius: 5px;  width:50%; height: 80px; line-height: 80px; margin: 20px; text-indent: 20px; border: 1px solid #cccccc;position: center;}
input,select,textarea{font-size: 30px;}
@-webkit-keyframes spin {
to {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes spin {
to {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
.div-waiting{
position: fixed;
z-index: 998;
top: 0;
right: 0;
bottom: 0;
left: 0;
opacity: 1;
background: rgba(0,0,0,0.2);
vertical-align: middle;
text-align: center;
}
.icon-waiting{
position: relative;
top: 48%;
width: 10rem;
height: 10rem;
margin: 0 auto;
border-radius: 50%;
border: 1rem solid rgba(21, 21, 21, 0.4);
border-top-color: #e1e1e1;
-webkit-animation: 1.5s spin infinite linear;
animation: 1.5s spin infinite linear;
}
</style>
<section id="container" class="msgdetail">
<ul id="myTab" class="nav nav-tabs"  style="font-size: 2rem;">
<li><a href="#list" data-toggle="tab"><h2>&nbsp;&nbsp;&nbsp;申请列表&nbsp;&nbsp;&nbsp;</h2></a></li>
<li><a href="#new" data-toggle="tab"><h2>&nbsp;&nbsp;&nbsp;新增xxx&nbsp;&nbsp;&nbsp;</h2></a></li>
</ul>
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade" id="list">
</div>
</div>
<div class="tab-pane fade" id="new">
<!--    <form action="" method="post" style="font-size: 2rem;"> -->
<input type="hidden" name="user_id" id="salement" value="{$personId}">
<div class="pay-rece-div">
<span>房源信息(搜索)</span>
<span>>></span>
<input type="text" name="house_name" id="house_name" data-toggle="modal" data-target="#myModal"  onclick="clearHouse()" readonly="readonly" placeholder="点击搜索公司在管房源,关联房源" class="txt">
<input type="hidden"name="house_id" id="house_id">
</div> 
<div class="pay-rece-div">
<span>收款人</span>
<span>>></span>
<input type="text"  id="payee_name" class="txt">
</div>
<div class="pay-rece-div">
<span>联系方式</span>
<span>>></span>
<input type="text"  id="payee_mobile" class="txt">
</div>
<div class="pay-rece-div">
<span>收款方式</span>
<span>>></span>
<select  class="txt" id="payment">
<option value="1">现金</option>
<option value="2">银行</option>
<option value="3">微信</option>
<option value="4">支付宝</option>
</select>
</div>
<div class="pay-rece-div">
<span>备注</span>
<span>>></span><br>
<textarea name="remark" id="remark" style="width: 90%;height: 240px;border: 1px solid #cccccc;font-size: 30px;"></textarea>
</div>
<div class="pay-rece-div">
<span>图片附件:</span>
<div class="addForm" id="pictureForm">
<table>
<tbody>
<tr class="photosDetail">
<td class="photos pic1" >
<img class="photo photo1" style="width: 80px;height: 80px;" src="__STATIC__images/camera.png" >
</td>
</tr>
</tbody>
</table>
<button class="btn2 btn-pay"  style="margin-top: 80px;" onclick="picture()">确认提交</button>
</div>
</div>
<!--  <input type="submit" id="subbut" class="btn2" style="width: 20rem" value="确认提交">-->
<div style="height: 3rem;"></div>
<!-- </form> -->
</div>
</div>
</section>
<!-- 模态框(Modal)搜索房源 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="font-size: 2.7rem">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<p class="modal-title" id="myModalLabel">房源搜索</p>
</div>
<div class="modal-body">
<input type="text" name="keywords" id="keyword" style="padding:  1rem;width: 45rem;"><button type="text" onclick="searchHouse()">搜索</button>
<button type="button" data-dismiss="modal">关闭</button>
<div id="houseList">
</div>
</div>
<div class="modal-footer">
<!-- <button type="button" class="btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn-primary">提交更改</button> -->
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<!-- 模态框(Modal)借款详情 -->
<div class="modal fade" id="loanModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="font-size: 2.7rem">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<h2 style="color: #00BFFF;">借款详情</h2>
<br/>
<div id="loanList">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-default" data-dismiss="modal">关闭</button>
<!--<button type="button" class="btn-primary">提交更改</button> -->
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<script>
function changetype(){
var type = $('#type').val();
if(type == 1){
$('#loan').attr("style",'display: block;');
$('#loan').attr("style",'color: red;');
$("#is_loan option[value='0']").attr("selected", true);
}
if (type ==2 || type == 0) {
$('#loan').attr("style",'display: none;');
$('#loanid').attr("style",'display: none;');
}
}
function changeloan(){
var loan = $('#is_loan').val();
if(loan == 1){
$('#loanid').attr("style",'display: block;');
$('#loanid').attr("style",'color: red;');
}
if (loan == 3 || loan == 0) {
$('#loanid').attr("style",'display: none;');
}
}
function changetcontractype(){
$("#contract_code").empty();
$.ajax({
type: "POST",
url: "/weixin/staff/getContract",
data: {
house_id:$('#house_id').val(),
contract_type:$('#contract_type').val(),
},
success: function(rzt) {
if (rzt.err) {
alert(rzt.msg);
}else{
var codeList = rzt.data;
console.log(rzt);
for (var i = 0 ; i < codeList.length ; i++){
$("#contract_code").append("<option value='"+codeList[i].id+"'>"+codeList[i].code+"</option>");
}
}
}
});
}
$(function(){
$('#myTab li:eq(1) a').tab('show');
for(var i = 1; i <= 8; i++) {
$(".addForm .photosDetail .photo").before('<input id="fileBtn_add' + i + '" type="file" onchange="upload(this,1,'+i+');" name="pictureName'+ i +'" accept="image/*" multiple class="fileBtn_add' + i + '" />');
}
/* $(".addForm .photoThumbnail .photo").before('<input id="fileBtn_add5" type="file" onchange="upload(this,2,5);" name="pictureName5" accept="image/*" multiple class="fileBtn_add5" />');
$(".addForm .photoBanner .photo").before('<input id="fileBtn_add6" type="file" onchange="upload(this,3,6);" name="pictureName6" accept="image/*" multiple  class="fileBtn_add6" />');*/
/* $("#img img").οnclick=function(){
nowurl=this.src;
console.log(nowurl);
console.log(nowurl);
wx.previewImage({
current: nowurl,
urls: nowurl
});       
}*/
});
var aCount = 0;
var bCount = 0;
var cCount = 0;
var image = new Array();
//添加图片
function upload(c,index,index2) {
"use strict";
var $c = c;
//console.log($c);
var $d = document.createElement('img');
var file = $c.files[0];
//console.log(file);
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
var w = index2 -1;
//20210413  压缩图片调用方法
dealImage(e.target.result,{width:800},function(base){
    //document.getElementById('img').setAttribute('src',base);
image[w] = base;
});
//20210413
//image[w] = e.target.result;//20210413
console.log(image);
$d.setAttribute("src", e.target.result);
$($d).addClass($($c).attr('class'));
//console.log($(".addForm .photos input").index(this) + 1);
var div = document.createElement('div');
div.className = 'tuPic';
$(div).append($d);
//var url = "__STATIC__images/del.png";
//$(div).append("<span class='delClose' onclick='delPic(this,"+index2+")'><img src="+url+" width=100%></span>");
$(div).append("<span class='delClose' onclick='delPic(this,"+index2+")'>x</span>");
/*if (index==1){
aCount++;
if (aCount==4){
$(".photo1").hide();
}
}else if(index==2){
bCount++;
$(".photo2").hide();
}else {
cCount++;
$(".photo3").hide();
}*/
$(".addForm .pic"+index).append(div);
$("#fileBtn_add"+index2).hide();
}
}
// 删除对应input框的缩略图和文件
function delPic(e,index2) {
var y = index2 - 1;
delete image[y];
resetFileInput($("#fileBtn_add"+index2));
/*switch (index2) {
case 1:
case 2:
case 3:
case 4:
aCount--;
if (aCount==3){
$(".photo1").show();
}
break;
case 5:
bCount--;
$(".photo2").show();
break;
case 6:
$(".photo3").show();
cCount--;
}*/
$(e).parent().remove();
$('#fileBtn_add'+index2).show();
}
//清除input框内的文件内容
function resetFileInput(file){
file.after(file.clone().val(""));
file.remove();
}
//点击提交上传图片
function picture(){  
$.ajax({
type: "POST",
url: "/weixin/staff/submitCommission",
data: {
house_id:$('#house_id').val(),
payment:$('#payment').val(),
payee_name:$('#payee_name').val(),
payee_mobile:$('#payee_mobile').val(),
bank:$('#bank').val(),
bank_account_name:$('#bank_account_name').val(),
bank_account:$('#bank_account').val(),
img:image,
salement_id:$('#salement').val(),
},
beforeSend:function(){
showWaiting();
},
success: function(rzt) {
console.log(rzt);
if (rzt.err) {
closeWaiting();
alert(rzt.err);
}else{
closeWaiting();
alert('提交成功');
$(".btn2").attr("disabled",'none');
window.location.reload();
}
}
});
}
function clearHouse(){
document.getElementById('keyword').value="";
document.getElementById('houseList').innerHTML=" "; 
/*$('#house_name').attr('value',"");
$('#house_id').attr('value',"");*/
}
function searchHouse(){
var keyword = document.getElementById('keyword').value;
$.ajax({
type: "POST",
url: "/weixin/staff/searchHouseList",
data: {
keyword: $("#keyword").val(),
},
dataType: "JSON",
success: function(result) {
houselist = result.data;
document.getElementById('houseList').innerHTML=houselist; 
}
});
}
function choseHouse(house_id,full_name){
$('#house_name').attr('value',full_name);
$('#house_id').attr('value',house_id);
}
function searchLoan(){
$.ajax({
type: "POST",
url: "/weixin/staff/getLoan",
data: {
house_id:$('#house_id').val(),
},
success: function(rzt) {
if (rzt.err) {
//$('#loanModal').modal(false);
alert(rzt.msg);
}else{
$('#loanModal').modal(true);
var loanList = rzt.data;
console.log(rzt);
document.getElementById('loanList').innerHTML=loanList; 
/*for (var i = 0 ; i < codeList.length ; i++){
$("#contract_code").append("<option value='"+codeList[i].id+"'>"+codeList[i].code+"</option>");
}*/
}
}
});
}
function choseLoan(id,name){
$('#loan_id').attr('value',id);
$('#loaner').attr('value',name);
}
function showWaiting(){
var node=document.createElement("div");  //创建一个div元素节点,作为整个背景的容器
var nodeClass=document.createAttribute("class"); //创建class元素属性
var nodeStyle = document.createAttribute("style"); //创建style元素属性
var nodeName = document.createAttribute("name"); //创建name元素属性
nodeName.value = "divWaiting"; //给元素节点命名
nodeClass.value = "div-waiting"; //元素属性赋值
nodeStyle.value = "height:"+window.innerHeight + "px; width:"+window.innerWidth+"px;";
node.setAttributeNode(nodeClass); //设置元素节点的属性及值
node.setAttributeNode(nodeStyle);
node.setAttributeNode(nodeName);
var iconNode = document.createElement("div");  //创建一个div元素节点,作为旋转图标的容器
var iconClass = document.createAttribute("class");
iconClass.value = "icon-waiting";
iconNode.setAttributeNode(iconClass);
node.appendChild(iconNode);  //将图标节点放到整个背景的元素节点
document.body.appendChild(node); //将整个背景div插入到body中
}
function closeWaiting(){
var wait = document.getElementsByName("divWaiting"); //获取name为divWaiting的元素节点
console.log(wait);
//遍历所有的节点,将body中的所有等待旋转效果去掉
for(var i=0; i<wait.length; i++){
document.body.removeChild(wait[i]);
}
}
//20210413
/**
* 图片压缩,默认同比例压缩
* @param {Object} path
* pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照相图片储存的绝对路径
* @param {Object} obj
* obj 对象 有 width, height, quality(0-1)
* @param {Object} callback
* 回调函数有一个参数,base64的字符串数据
*/
function dealImage(path, obj, callback){
var img = new Image();
img.src = path;
img.onload = function(){
var that = this;
// 默认按比例压缩
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
var quality = 1; // 默认图片质量为0.7
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 图像质量
if(obj.quality && obj.quality <= 1 && obj.quality > 0){
quality = obj.quality;
}
// quality值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality );
// 回调函数返回base64的值
callback(base64);
}
}
</script>

2,后端PHP上传代码

   public function imageBase64Upload($base64_img,$fun = ''){
header("content-type:text/html;charset=utf-8");
//$base64_img = trim($_POST['img']);
//var_dump($base64_img);
$path_name = 'uploads'. DS . date('Ymd') . DS . $fun . DS;
$file_name = date('YmdHis_').rand(1,1000).'_'.$fun.'.';
$up_dir = ROOT_PATH .'public' . DS . $path_name;
$res = true;
//$up_dir = './upload/';//存放在当前目录的upload文件夹下
if(!file_exists($up_dir)){
$res = mkdir($up_dir,0777,true);
}
if(!$res){
$this->_error(1,'文件上传失败,原因:没有权限创建目录');
}
if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
$type = $result[2];
if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
$file_name = $file_name.$type;
//$new_file = $up_dir.date('YmdHis_').rand(1,100).'_loan.'.$type;
$new_file = $up_dir.$file_name;
if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
//$img_path = str_replace('../../..', '', $new_file);
$img_path = '/'.$path_name.$file_name;
return $img_path;
//$this->_error(0,'上传成功',$img_path);
//echo '图片上传成功</br>![](' .$img_path. ')';
}else{
//echo '图片上传失败</br>';
$this->_error(1,'文件上传失败,原因:文件写入失败');
}
}else{
//文件类型错误
//echo '图片上传类型错误';
$this->_error(1,'文件上传类型错误');
}
}else{
//文件错误
//echo '文件错误';
$this->_error(1,'文件错误');
}
}

3,分拆前端上传代码

1)html部分

 <div class="addForm" id="pictureForm">
<table>
<tbody>
<tr class="photosDetail">
<td class="photos pic1" >
<img class="photo photo1" style="width: 80px;height: 80px;" src="__STATIC__images/camera.png" >
</td>
</tr>
</tbody>
</table>
<button class="btn2 btn-pay"  style="margin-top: 80px;" onclick="picture()">确认提交</button>
</div>

2)就js部分

 $(function(){
$('#myTab li:eq(1) a').tab('show');
for(var i = 1; i <= 8; i++) {
$(".addForm .photosDetail .photo").before('<input id="fileBtn_add' + i + '" type="file" onchange="upload(this,1,'+i+');" name="pictureName'+ i +'" accept="image/*" multiple class="fileBtn_add' + i + '" />');
}
/* $(".addForm .photoThumbnail .photo").before('<input id="fileBtn_add5" type="file" onchange="upload(this,2,5);" name="pictureName5" accept="image/*" multiple class="fileBtn_add5" />');
$(".addForm .photoBanner .photo").before('<input id="fileBtn_add6" type="file" onchange="upload(this,3,6);" name="pictureName6" accept="image/*" multiple  class="fileBtn_add6" />');*/
/* $("#img img").οnclick=function(){
nowurl=this.src;
console.log(nowurl);
console.log(nowurl);
wx.previewImage({
current: nowurl,
urls: nowurl
});       
}*/
});
var aCount = 0;
var bCount = 0;
var cCount = 0;
var image = new Array();
//添加图片
function upload(c,index,index2) {
"use strict";
var $c = c;
//console.log($c);
var $d = document.createElement('img');
var file = $c.files[0];
//console.log(file);
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
var w = index2 -1;
//20210413
dealImage(e.target.result,{width:800},function(base){
    //document.getElementById('img').setAttribute('src',base);
image[w] = base;
});
//20210413
//image[w] = e.target.result;//20210413
console.log(image);
$d.setAttribute("src", e.target.result);
$($d).addClass($($c).attr('class'));
//console.log($(".addForm .photos input").index(this) + 1);
var div = document.createElement('div');
div.className = 'tuPic';
$(div).append($d);
//var url = "__STATIC__images/del.png";
//$(div).append("<span class='delClose' onclick='delPic(this,"+index2+")'><img src="+url+" width=100%></span>");
$(div).append("<span class='delClose' onclick='delPic(this,"+index2+")'>x</span>");
/*if (index==1){
aCount++;
if (aCount==4){
$(".photo1").hide();
}
}else if(index==2){
bCount++;
$(".photo2").hide();
}else {
cCount++;
$(".photo3").hide();
}*/
$(".addForm .pic"+index).append(div);
$("#fileBtn_add"+index2).hide();
}
}
// 删除对应input框的缩略图和文件
function delPic(e,index2) {
var y = index2 - 1;
delete image[y];
resetFileInput($("#fileBtn_add"+index2));
/*switch (index2) {
case 1:
case 2:
case 3:
case 4:
aCount--;
if (aCount==3){
$(".photo1").show();
}
break;
case 5:
bCount--;
$(".photo2").show();
break;
case 6:
$(".photo3").show();
cCount--;
}*/
$(e).parent().remove();
$('#fileBtn_add'+index2).show();
}
//清除input框内的文件内容
function resetFileInput(file){
file.after(file.clone().val(""));
file.remove();
}

3,css部分

   .photos input[type='file'] {
opacity: 0;
position: absolute;
left: 0;
top: 0;
}
.photos img, .photos input[type='file'] {
width: 150px;
height: 150px;
margin-right: 30px;
margin-top: 10px;
transition: all .4s;
}
td{
position: relative;
height: 150px;
left: 20px;
top:20px;
width: 550px
}
.photos div {
display: inline-block;
width: 150px;
height: 150px;
margin-right: 30px;
position: relative;
}
.delClose{
height: 35px;
width: 35px;
background-color:#757B81;
border-radius:50%;
position: absolute;
right: 0;
top: 0px;
line-height: 35px;
color:white;
text-align: center;
}

4,js提交后端请求转圈等待代码

js部分:
function showWaiting(){
var node=document.createElement("div");  //创建一个div元素节点,作为整个背景的容器
var nodeClass=document.createAttribute("class"); //创建class元素属性
var nodeStyle = document.createAttribute("style"); //创建style元素属性
var nodeName = document.createAttribute("name"); //创建name元素属性
nodeName.value = "divWaiting"; //给元素节点命名
nodeClass.value = "div-waiting"; //元素属性赋值
nodeStyle.value = "height:"+window.innerHeight + "px; width:"+window.innerWidth+"px;";
node.setAttributeNode(nodeClass); //设置元素节点的属性及值
node.setAttributeNode(nodeStyle);
node.setAttributeNode(nodeName);
var iconNode = document.createElement("div");  //创建一个div元素节点,作为旋转图标的容器
var iconClass = document.createAttribute("class");
iconClass.value = "icon-waiting";
iconNode.setAttributeNode(iconClass);
node.appendChild(iconNode);  //将图标节点放到整个背景的元素节点
document.body.appendChild(node); //将整个背景div插入到body中
}
function closeWaiting(){
var wait = document.getElementsByName("divWaiting"); //获取name为divWaiting的元素节点
console.log(wait);
//遍历所有的节点,将body中的所有等待旋转效果去掉
for(var i=0; i<wait.length; i++){
document.body.removeChild(wait[i]);
}
}
css部分:
@-webkit-keyframes spin {
to {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes spin {
to {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
.div-waiting{
position: fixed;
z-index: 998;
top: 0;
right: 0;
bottom: 0;
left: 0;
opacity: 1;
background: rgba(0,0,0,0.2);
vertical-align: middle;
text-align: center;
}
.icon-waiting{
position: relative;
top: 48%;
width: 10rem;
height: 10rem;
margin: 0 auto;
border-radius: 50%;
border: 1rem solid rgba(21, 21, 21, 0.4);
border-top-color: #e1e1e1;
-webkit-animation: 1.5s spin infinite linear;
animation: 1.5s spin infinite linear;
}

5,压缩图片代码:

   /**
* 图片压缩,默认同比例压缩
* @param {Object} path
* pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照相图片储存的绝对路径
* @param {Object} obj
* obj 对象 有 width, height, quality(0-1)
* @param {Object} callback
* 回调函数有一个参数,base64的字符串数据
*/
function dealImage(path, obj, callback){
var img = new Image();
img.src = path;
img.onload = function(){
var that = this;
// 默认按比例压缩
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
var quality = 1; // 默认图片质量为0.7
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 图像质量
if(obj.quality && obj.quality <= 1 && obj.quality > 0){
quality = obj.quality;
}
// quality值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality );
// 回调函数返回base64的值
callback(base64);
}
}

回复

我来回复
  • 暂无回复内容