Html jq 图片(大小判断)上传 删除

226 阅读3分钟

##简介 Android开发仔一枚,以前只是简单的使用webview添加过简单js代码,这是第 一次完全的抛弃Andoird,下面我会写一篇基于原声Html input jq + java 后端的博客。小生不才,如有错误麻烦大佬留言。

html 前端

<div class="upload">
         <label id="titleG">用户照片上传</label>
<div>
			<span style="font-size: 0.25rem;">*上传要求:请上传每张5M以内、最多5张照片,一次仅能上传一张</span>
			</div>
            <div id="ct2">
				<div class="z_file">
					<span class="ver"></span>
						<span></span>
					<input type="file" name="file" id="file" value="" accept="image/*" multiple  />
						
				</div>
            </div>

        </div>

上述代码,就是比较经典也是最简单的 input html代码,type 需要选择为file,name也是要加上的,后边会和后台代码比对名称的环节。 accept="image/*" multiple ,选择文件类型为图片类型。

javascript 代码

大段js代码来袭,预警 over。

$('#file').off('change').on('change', function() {
		var tmp_file = document.getElementById("file").files[0];
		var file_name = tmp_file.name;
		var suffixIndex=file_name.lastIndexOf(".");  
        var suffix=file_name.substring(suffixIndex+1).toUpperCase();  
		if (typeof(tmp_file) == undefined) {
			return;
		}
		if(allImgUrl.length>=5){
			mui.toast('抱歉不能上传更多照片',{ duration:'1000', type:'div' });
			return;
		}
		if(tmp_file.type.indexOf("image/")==-1){
			mui.toast('请选择图片类型文件-.-',{ duration:'1000', type:'div' });
			return;
		}
		if(suffix!="BMP"&&suffix!="JPG"&&suffix!="JPEG"&&suffix!="PNG"&&suffix!="GIF"){
			mui.toast('请选择图片类型文件',{ duration:'1000', type:'div' });
			return;
		}
		var reader = new FileReader();
		reader.readAsDataURL(tmp_file);
		reader.onload = function(theFile) {
          var image = new Image();
            image.src = theFile.target.result;
            image.onload = function() {
            if(this.width>10000){
				mui.toast('图片宽度大于10000',{ duration:'1000', type:'div' });
                return;
            }
            if(this.height>10000){
                mui.toast('图片高度大于10000',{ duration:'1000', type:'div' });
                return;
            }
             //alert("图片的宽度为"+this.width+",长度为"+this.height);
           };
		};
		if(tmp_file.size>5120000){
			mui.toast('图片大小不超过5M',{ duration:'1000', type:'div' });
            return;
		}
		var form = new FormData();
		form.append('file', tmp_file);
	
		
		$.ajax({
			url: YOU URL ,
			method: "POST", //接口方法  
			params: {},
			data: form,
			// 下边两句是必须加的,好像是防止内容被编译
			processData: false,
			contentType: false,
			headers: {
				'Bear': utils.getCookie('token') ,
				'content-type': undefined,
				'channel': 'fudan0002'
			}
		}).then(function(response) {
			console.log(response);
			$('input[type=file]').wrap('<form>').closest('form').get(0).reset();
			var str = response.split("data")[1];
			var imgurl = str.slice(3);
			imgurl = imgurl.substring(0,imgurl.length-2);
			allImgUrl.push(imgurl);
			var photoId = "photo_id"+(allImgUrl.length-1);
            $("#ct2").append(`<img src="${imgurl}" id="${photoId}" class="photo-swipe" style="height: .92rem;border:1px solid #e0e0e0;margin-bottom: .1rem;margin-right: .1rem;">`);
			$(".photo-swipe").mousedown(function() {  
				var clickId = this.id;
				allImgUrl.splice(this.src);
				timeout = setTimeout(function() {
					mui.confirm('确定要撤销这个工单吗','提示',['取消','确认'],function(e){
                    if ( e.index == 1 ) {
                       $("#"+clickId).hide();
                    }   
				})
				}, 500); 
				 
			});
			 
   
			/*$(".photo-swipe").mouseup(function() {  
				clearTimeout(timeout);  
				console.log("out");
			});  
  
			$(".photo-swipe").mouseout(function() {  
				clearTimeout(timeout);  
				console.log("out");
			});  
			*/
		});
	});

上述代码是我直接从项目中粘贴出来的,个人小白能力,所以代码有点垃圾...,我们一起来看下代码。首先我们对上传文件的控件添加 改变监听事件,我们选择的文件都会在 files 已数组的方式存储,我这边需求单张上传,所以获取的第一个位置,如果你们需要多张上传的话,可以直接获取files中的数组信息,来进行下一步的处理。 我这边分别对稳健进行了一下判断:

1.对图片个数 类型进行了判断

if(tmp_file.type.indexOf("image/")==-1){
			mui.toast('请选择图片类型文件-.-',{ duration:'1000', type:'div' });
			return;
		}
if(suffix!="BMP"&&suffix!="JPG"&&suffix!="JPEG"&&suffix!="PNG"&&suffix!="GIF"){
			mui.toast('请选择图片类型文件',{ duration:'1000', type:'div' });
			return;
		}

2 通过FileReadr方式 判断宽高信息

var reader = new FileReader();
		reader.readAsDataURL(tmp_file);
		reader.onload = function(theFile) {
          var image = new Image();
            image.src = theFile.target.result;
            image.onload = function() {
            if(this.width>10000){
				mui.toast('图片宽度大于10000',{ duration:'1000', type:'div' });
                return;
            }
            if(this.height>10000){
                mui.toast('图片高度大于10000',{ duration:'1000', type:'div' });
                return;
            }
             //alert("图片的宽度为"+this.width+",长度为"+this.height);
           };
		};

3 对图片大小进行判断

if(tmp_file.size>5120000){
			mui.toast('图片大小不超过5M',{ duration:'1000', type:'div' });
            return;
		}

接下来的就是通过 ajax对图片进行上传,下文我们将我后端的代码贴上来,前后端都自己搞,真的很累,虽然我是一个菜鸟android。

在请求成功后我们获取到图片的存储地址。这个时候我们添加一段代码,$('input[type=file]').wrap('

').closest('form').get(0).reset(); 这段代码是改变inpout的type内容的,防止一次提交两次图片,第二次图片提交的时候发现 内容没有变化(因为我们监听方法是change)做出的调整,让他可以检测到相同的图片也可以提交。

请求成功后 我们这里动态的赋值img 的id,并在界面中显示出来,并给img 添加 长按事件,用来删除图片,我这里使用了 mui的弹框,点击确定 就获取id设置为 hide,并且移除 图片src 数组中 该图片的 url路径。以此来达到删除图片的效果。

Java端代码

/**
	 * 文件上传到服务器
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws FUDanException
	 */
	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST, headers = "Content-Type=multipart/form-data")
	@ResponseBody
	public Response<Object> uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException, FUDanException {
		Response<Object> response = new Response<Object>();
		if (!file.isEmpty()) {
			String filePath = System.currentTimeMillis()+"";
			// windows request.getSession().getServletContext().getRealPath(filePath)
			//String savePath = Constants.IMG_LOCATION_TEST+filePath;
			// linux 
			String savePath = Constants.IMG_LOCATION+filePath;
			File targetFile = new File(savePath);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			file.transferTo(targetFile);
			response.setCode(APIConstants.OK.getCode());
			response.setMsg(APIConstants.OK.getMsg());
			response.setData(Constants.HTTP_IMG_URL+filePath);
			//response.setData(Constants.HTTPS_IMG_URL+filePath);
			//response.setData(Constants.HTTP_IMG_URL_TEST+filePath);
		}else {
			response.setCode(APIConstants.FILE_UPLOAD_ERR.getCode());
			response.setMsg(APIConstants.FILE_UPLOAD_ERR.getMsg());
			response.setData("");
		}
		return response;
	}

后端代码需要注意的也就是 file的名称 要和前端的name相对应,其他的代码都是比较平常的代码。

到这里我的笔记总结也就写完了,本篇文章属于入门级别的,当然也希望有大佬提出宝贵意见一起学习进步。

(●─●)