当前代码功能有一些缺陷,可以关注最新的博客进行查看(https://www.cnblogs.com/yulongcode/p/12442054.html),如果您有兴趣,可以自己研究研究,欢迎沟通交流

====================================================================================

涉及知识:base64处理图片,ajax,js,thinkphp

效果图:

代码实现:

html:

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>showImages</title>
<style type="text/css">
.float{
float:left;
width : 200px;
height: 200px;
overflow: hidden;
border: 1px solid #CCCCCC;
border-radius: 10px;
padding: 5px;
margin: 5px;
}
img{
position: relative;
}
.result{
width: 200px;
height: 200px;
text-align: center;
box-sizing: border-box;
}
#file_input{
display: none;
}
.delete{
width: 200px;
height:200px;
position: absolute;
text-align: center;
line-height: 200px;
z-index: 10;
font-size: 30px;
background-color: rgba(255,255,255,0.8);
color: #777;
opacity: 0;
transition-duration: :0.7s;
-webkit-transition-duration: 0.7s;
}
.delete:hover{
cursor: pointer;
opacity: 1;
}
</style>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
window.onload = function(){
var input = document.getElementById("file_input");
var result;
var dataArr = []; // 储存所选图片的结果(文件名和base64数据)
var fd; //FormData方式发送请求
var oSelect = document.getElementById("select");
var oAdd = document.getElementById("add");
var oSubmit = document.getElementById("submit");
var oInput = document.getElementById("file_input"); if(typeof FileReader==='undefined'){
alert("抱歉,你的浏览器不支持 FileReader");
input.setAttribute('disabled','disabled');
}else{
input.addEventListener('change',readFile,false);
}     //handler function readFile(){
fd = new FormData();
var iLen = this.files.length;
var index = 0;
for(var i=0;i<iLen;i++){
if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)){  //判断上传文件格式
return alert("上传的图片格式不正确,请重新选择");
}
var reader = new FileReader();
reader.index = i;
fd.append(i,this.files[i]);
reader.readAsDataURL(this.files[i]); //转成base64
reader.fileName = this.files[i].name; reader.onload = function(e){
var imgMsg = {
name : this.fileName,//获取文件名
base64 : this.result //reader.readAsDataURL方法执行完后,base64数据储存在reader.result里
}
dataArr.push(imgMsg);
result = '<div class="delete">delete</div><div class="result"><img src="'+this.result+'" alt=""/></div>';
var div = document.createElement('div');
div.innerHTML = result;
div['className'] = 'float';
div['index'] = index;
document.getElementsByTagName('body')[0].appendChild(div);   //插入dom树
var img = div.getElementsByTagName('img')[0];
img.onload = function(){
var nowHeight = ReSizePic(this); //设置图片大小
this.parentNode.style.display = 'block';
var oParent = this.parentNode;
if(nowHeight){
oParent.style.paddingTop = (oParent.offsetHeight - nowHeight)/2 + 'px';
}
} div.onclick = function(){
this.remove(); // 在页面中删除该图片元素
delete dataArr[this.index]; // 删除dataArr对应的数据 }
index++;
}
}
} function send(){
var submitArr = [];
for (var i = 0; i < dataArr.length; i++) {
if (dataArr[i]) {
submitArr.push(dataArr[i]);
}
}
// console.log('提交的数据:'+JSON.stringify(submitArr))
$.ajax({
type : "post",
url : "{:URL('index/Index/index')}",
data : {
img : JSON.stringify(submitArr)
},
// processData: false, //用FormData传fd时需有这两项
// contentType: false,
success : function(data){
// console.log('返回的数据:'+data);
if(data ==1)
{
alert('yes');
}else {
alert('no');
}
}
})
} oSelect.onclick=function(){
oInput.value = ""; // 先将oInput值清空,否则选择图片与上次相同时change事件不会触发
//清空已选图片
$('.float').remove();
dataArr = [];
index = 0;
oInput.click();
} oAdd.onclick=function(){
oInput.value = ""; // 先将oInput值清空,否则选择图片与上次相同时change事件不会触发
oInput.click();
} oSubmit.onclick=function(){
if(!dataArr.length){
return alert('请先选择文件');
}
send();
}
}
/*
用ajax发送fd参数时要告诉jQuery不要去处理发送的数据,
不要去设置Content-Type请求头才可以发送成功,否则会报“Illegal invocation”的错误,
也就是非法调用,所以要加上“processData: false,contentType: false,”
* */ function ReSizePic(ThisPic) {
var RePicWidth = 200; //这里修改为您想显示的宽度值 var TrueWidth = ThisPic.width; //图片实际宽度
var TrueHeight = ThisPic.height; //图片实际高度 if(TrueWidth>TrueHeight){
//宽大于高
var reWidth = RePicWidth;
ThisPic.width = reWidth;
//垂直居中
var nowHeight = TrueHeight * (reWidth/TrueWidth);
return nowHeight; //将图片修改后的高度返回,供垂直居中用
}else{
//宽小于高
var reHeight = RePicWidth;
ThisPic.height = reHeight;
}
}
</script>
</head>
<body>
<div class="container">
<label>请选择一个图像文件:</label>
<button id="select">(重新)选择图片</button>
<button id="add">(追加)图片</button> <form action="" >
<input type="file" id="file_input" name="image[]" multiple/>
<!--用input标签并选择type=file,记得带上multiple,不然就只能单选图片了-->
<button id="submit">提交</button>
</form> </div>
</body>
</html>

php:

<?php
namespace app\index\controller; use think\Controller;
use think\Db; class Index extends Controller
{
public function index()
{
if(request()->isAjax())
{
$img = request()->post('img'); //接收图片信息
$arr = json_decode($img,true); //转成数组
$ImgUrl = [];
for($i=0;$i<count($arr);$i++)
{
$houzhui = substr(strrchr($arr[$i]['name'], '.'), 1);//获取文件后缀名
$image = $arr[$i]['base64'];
//这里的图片名称就是你存入数据库时的图片名称
$imageName = date("His",time())."_".rand(1111,9999).'.'.$houzhui;
// 判断是否有逗号 如果有就截取后半部分
if (strstr($image,",")){
$image = explode(',',$image);
$image = $image[1];
}
//图片保存路径,可根据使用框架目录的不同自定义目录
$path = ROOT_PATH . 'public' . DS .'static'. DS .date("Ymd",time());
// 判断目录是否存在 不存在就创建 并赋予777权限
if (!is_dir($path)){ //判断目录是否存在 不存在就创建
mkdir($path,0777,true);
}
$imageSrc= $path."/". $imageName;
// 生成图片 返回的是字节数
$r = file_put_contents($imageSrc, base64_decode($image));
if (!$r) {
$ImgUrl[$i] = "===图片生成失败===";
}else{
$ImgUrl[$i] = $imageName;
}
}
//$ImgUrl 即为上传之后的图片名称,是逗号隔开的字符串
$ImgUrl = implode(',',$ImgUrl);
//将字符串存入数据库
$data = Db::table('testimg')->insert(['val'=>$ImgUrl]);
if($data)
{
return 1;
}else{
return 0;
}
}else{
return view();
}
}
}

over!over!over!

最新文章

  1. Spring学习记录(九)---通过工厂方法配置bean
  2. angular2 - content projection-
  3. [Tips] JavaScript 使用hash 对象传参
  4. NaN
  5. Java基础之在窗口中绘图——绘制直线和矩形(Sketcher 2 drawing lines and rectangles)
  6. 文章投稿 latex 生成 pdf的字体Embeded问题解决(转自兵马俑BBS)
  7. GridView编辑删除操作
  8. android复合控件
  9. linux 定时执行 cron指令
  10. web.xml(7)_mime-mapping、welcome-file-list、error-page
  11. PhpForm表单相关的超全局变量操作
  12. win使用telnet到ubuntu下vim显示中文为乱码的解决方法~
  13. 《JavaScript高级程序设计》读书笔记 ---语句
  14. webservice时间类型XMLGregorianCalendar和Date的转换
  15. UVA11082:Matrix Decompressing
  16. 局域网ARP攻击防护
  17. Spring笔记 #01# 一个小而生动的IOC例子代码
  18. 无旋treap
  19. TOP100summit:【分享实录-美团点评】 业务快速升级发展背后的系统架构演进
  20. React Native开源项目如何运行(转载)

热门文章

  1. HTML5即将迎来黄金时代 轻应用再成行业焦点
  2. 在与SQL Server 建立 连接时出现与网络相关的或特定于实例的错误。未找到或无法访问服务器
  3. Unity3d 新建xml 读取xml
  4. sort_action
  5. Ubuntu搜狗输入法候选词乱码
  6. 判断Java数组是否包含某个值
  7. A Windows GUI for Appium
  8. Java+Jsoup实现网页内容抓取
  9. js实现菜单二级联动
  10. android4.3 蓝牙BLE编程