HTML5 多图片上传(前端+后台详解)
- 1、参考jquery插件库
- 2、修改代码
- 3、添加的后台代码
- 4、删除的后台代码
1、参考jquery插件库
手机端实现多图片上传
2、修改代码
我发现他这里的代码仅仅只是显示出来了,对后台一点作用都没有,于是我对该代码进行了修改
注意:我这里用了vue.js,直接用可能有些地方会报错,请大家修改后使用
imgChange :function (obj1, obj2,id) {var id = id;//console.info(id);//获取点击的文本框var file = document.getElementById(id);//存放图片的父级元素var imgContainer = document.getElementById(obj1);//获取的图片文件var fileList = file.files;//文本框的父级元素var input = document.getElementById(obj2);var imgArr = [];//var imgUrlArr = [];//遍历获取到得图片文件for (var i = 0; i < fileList.length; i++) {var imgUrl = window.URL.createObjectURL(file.files[i]);//console.info(imgUrl);//回显图片var imgList = document.getElementsByClassName("z_addImg");imgArr.push(imgUrl);var img = document.createElement("img");img.setAttribute("src", imgArr[i]);img.setAttribute("id",id+"_"+(imgList.length+1));var imgAdd = document.createElement("div");imgAdd.setAttribute("class", "z_addImg");imgAdd.appendChild(img);imgContainer.appendChild(imgAdd);//下面的这段代码是我自己添加的,每添加一张图片就上传到服务器并给数据库插入一条记录//思路大概是把我们上传的图片转成base64的格式,然后把base64放进dealImage()方法中进行压缩,因为有的图片可能很大,这个时候我们需要把图片压缩一下,不想压缩的就把dealImage()方法删掉就好了。//把图片转成base64然后上传var base64 = "";var str = "";var dealImage = this.dealImage;var reader = new FileReader();reader.readAsDataURL(file.files[i]);reader.onload = function(){base64 = this.result;dealImage(base64, 500, useImg);function useImg(base64) {str= base64;//这个就是我们最后需要的http({data: {encode:base64},url: 'projectFile/saveCheckPhoto',type: 'post',dataType: 'json',async: false,success: function(data) {}})};};};this.imgRemove();},// 压缩图片
dealImage :function (base64, w, callback) {var newImage = new Image();var quality = 0.6; //压缩系数0-1之间newImage.src = base64;newImage.setAttribute("crossOrigin", 'Anonymous'); //url为外域时需要var imgWidth, imgHeight;newImage.onload = function () {imgWidth = this.width;imgHeight = this.height;var canvas = document.createElement("canvas");var ctx = canvas.getContext("2d");if (Math.max(imgWidth, imgHeight) > w) {if (imgWidth > imgHeight) {canvas.width = w;canvas.height = w * imgHeight / imgWidth;} else {canvas.height = w;canvas.width = w * imgWidth / imgHeight;}} else {canvas.width = imgWidth;canvas.height = imgHeight;quality = 0.6;}ctx.clearRect(0, 0, canvas.width, canvas.height);ctx.drawImage(this, 0, 0, canvas.width, canvas.height);var base64 = canvas.toDataURL("image/*", quality); //压缩语句// 如想确保图片压缩到自己想要的尺寸,如要求在50-150kb之间,请加以下语句,quality初始值根据情况自定// while (base64.length / 1024 > 150) {// quality -= 0.01;// base64 = canvas.toDataURL("image/jpeg", quality);// }// 防止最后一次压缩低于最低尺寸,只要quality递减合理,无需考虑// while (base64.length / 1024 < 50) {// quality += 0.001;// base64 = canvas.toDataURL("image/jpeg", quality);// }callback(base64);//必须通过回调函数返回,否则无法及时拿到该值}
},//删除
imgRemove:function () {var projectId = getQueryString("projectId");var institutionsId = getQueryString("institutionsId");var imgList = document.getElementsByClassName("z_addImg");var mask = document.getElementsByClassName("z_mask")[0];var cancel = document.getElementsByClassName("z_cancel")[0];var sure = document.getElementsByClassName("z_sure")[0];for (var j = 0; j < imgList.length; j++) {imgList[j].index = j;imgList[j].onclick = function() {var t = this;mask.style.display = "block";cancel.onclick = function() {mask.style.display = "none";};sure.onclick = function() {mask.style.display = "none";t.style.display = "none";//在这里我进行了一个删除操作,把数据库和服务器上的图片给删掉//这个为该图片的id,用来区分具体为那个图片var imgId = $(t).find("img").attr("id");//这个是删除方法,同时删除服务器文件和数据库记录http({data: {originalName:imgId,projectId: projectId,institutionsId: institutionsId,},url: 'projectFile/deleteCheckPhoto',type: 'post',dataType: 'json',async: false,success: function(data) {}})};}};
}
3、添加的后台代码
后台代码仅供参考
这个是在yml中定义的,我定义的是D:/file下面。你也可以直接写死
@Value("${store.dir}")private String storeDir;public Result saveCheckPhoto(ProjectFile projectFile){Result result = new Result();SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");String fileAdd = sdf.format(new Date());//图片名称是 当前日期 避免数据重复String fileName = fileAdd + ".jpg";//这个步骤是把base64转成图片,并存在storeDir+"/checkPhoto/"+fileName这个目录下,这个storeDir是我们自己定义的,比如这个是D:/fileBase64ToPicture.GenerateImage(projectFile.getEncode(),storeDir+"/checkPhoto/"+fileName);String url = "/res/file/get/" + "checkPhoto" + "/" + fileName;projectFile.setId(UUIDTool.createUUID());projectFile.setUrl(url);projectFile.setCreateTime(new Date());projectFile.setFileType("jpg");projectFile.setType("checkPhoto");projectFile.setName(fileName);projectFileMapper.insert(projectFile);result.setMessage("保存成功!");result.setCode(1);return result;}
在这里面有个Base64ToPicture方法,以及以后需要显示,这个时候大家可以去看我以前的写一篇文章
jSignature签名的用法,一文教会你(二)后台代码
这篇博文详细讲解了我们需要用到什么工具类以及怎么回显;
4、删除的后台代码
public Result deleteCheckPhoto(ProjectFile projectFile){Result result = new Result();String contentId = projectFile.getOriginalName().substring(0,32); List<ProjectFile> list = projectFileMapper.queryCheckPhoto(projectFile);//这里是为了防止空指针if(list.size()>0){UploadUtil.delete(list.get(0).getUrl(),"D://ms_file");int count = projectFileMapper.deleteByPrimaryKey(list.get(0).getId());}result.setMessage("删除成功!");result.setCode(1);return result;
}
UploadUtil方法也在jSignature签名的用法,一文教会你(二)后台代码博文里。