图片上传(方法一:jquery.upload.js)
一、在JSP页面引入jquery.upload.js 文件:
<script type="text/javascript" src="${ctx}/script/jquery.upload.js"></script>
二、JSP页面代码:
<!-- 弹窗 开始 --> <div class="dialog_teachermanage" id="addDialog" style="width:923px; display:none" > <div class="dialog_title" data-operateType="add"></div> <form id="formId" method="post" enctype="multipart/form-data"> <div class="dialog_body"> <div class="left"> <!-- 上传头像 ajax提交 class="hide" --> <div class="head_photo"> <input type="button" id="head_pic_btn" value="点击上传头像" /> <img src="${ctx}/static/images/common/head_default.jpg" data-img="head_default.jpg" width="180px" height="210px" id="head_img" /> </div> <!-- 上传头像 form提交 --> <!-- <div class="tphoto" name="head_img" id="head_img"> <input type="file" name="file" id="file" onchange="previewImage(this)" /> <div id="preview"> <img id="imghead" border="1" width="100px;" heigh="100px;" src='${ctx}/static/images/common/head_default.jpg'> </div> </div> --> <div class="clear" style="height:30px;"></div> <!-- 隐藏的标签查询、输入框 --> <div class="addsign" id="addCourse"> <div class="tagdiv"> <a class="addtag"><i class='iconfont'></i>添加标签</a> <div class="taginput clearfix"> <input class="form-control" id="tagName" type="text" /> <i class="iconfont ok" id="addtag-ok"></i> <i class="iconfont cancel" id="addtag-cancel"></i> </div> </div> </div> <ul class="singul labels" name="labels" id="labels"></ul> </div> <div class="right"> <input type="hidden" id="id"> <div class="right_tinput"> <span class="t_span">姓名</span> <input type="text" name="name" id="name" data-rule="required;length[1~30]" data-tip="30字以内"/> </div> <div class="right_tinput"> <span class="t_span">头衔</span> <input type="text" name="title" id="title" data-rule="length[0~30]" data-tip="30字以内"/> </div> <div class="right_tinput"> <span class="t_span">电话</span> <input type="text" name="phone" id="phone" data-rule="mobile" data-rule-mobile="[/^1[3458]\d{9}$/, '请检查手机号格式']" /> </div> <div class="right_tinput"> <span class="t_span">邮箱地址</span> <input type="text" name="email" id="email" data-rule="email;length[0~50];"/> </div> <div class="right_tinput"> <span class="t_span">讲师类型</span> <select id="trainerTypeId_add" name="trainerTypeId" placeholder="请选择"/></select> </div> <div class="right_tinput"> <span class="t_span">专业领域</span> <textarea cols="46" rows="5" placeholder="限200字" name="proField" id="proField" data-rule="length[0~200]"></textarea> </div> <div class="right_tinput"> <span class="t_span">简介</span> <textarea cols="46" rows="5" placeholder="限200字" name="intro" id="intro" data-rule="length[0~200]"></textarea> </div> </div> </div> <div class="dialog_bottom"> <div class="buttons"> <button type="button" id="cancel">取消</button> <button type="submit" >保存</button> </div> </div> </form> </div> <!-- 弹窗 结束 -->
三:JS代码:
<script type="text/javascript" > $(function(){ //点击上传头像 $("#head_pic_btn").click(function(){ $.upload({ url:'${ctx}/td/trainer/uploadHeadImg.do', fileName:'img', dataType:'json', onComplate:function(data){ //删除data中<pre>标签 var start = data.indexOf(">"); if (start != -1) { var end = data.indexOf("<", start + 1); if (end != -1) { data = data.substring(start + 1, end); } } if(data!==''){ //$("#head_pic_btn").hide(); //$("#head_img").show().attr('src',"${ctx}/upload/trainer_picture/"+data); $("#head_img").attr("src","${ctx}/upload/trainer_picture/"+data); $("#head_img").attr("data-img",data); /** data=JSON.parse( data.match(/{.+}/)[0] ) if( data.result==='true' ){ $('#head_pic_btn').hide(); $('#head_img').show().attr('src',"${ctx}/upload/trainer_picture/"+data); }; alert(data.resultDesc); */ }; } }); }); });
四、JS提交代码(带预览效果):
//新增修改 验证提交 $("#formId").validator({ theme :"simple_bottom", valid: function(form){ var tname=$(".dialog_title").text(); if(tname.indexOf("修改")>=0){ //修改保存 //SaveEditTeacher(); var labels = ""; var index = 0; $(".labels").find("li").each(function(){ if(index==0){ labels += "'" + $(this).attr("data-id") + "'"; }else{ labels += ",'"+$(this).attr("data-id") + "'"; } index++; }); var param={headImg:$("#head_img").attr("data-img"),name:$("#name").val(),title:$("#title").val(),phone:$("#phone").val(),email:$("#email").val(),proField:$("#proField").val(),trainerTypeId:$("#trainerTypeId").val(),address:$("#address").val(),intro:$("#intro").val(),labels:labels }; $.ajax({ url:"${ctx}/td/trainer/modify.do", type:"get", data:param, success:function(data){ if(data.result=="true"){ new AlertWin().initfn({ "tipscon":data.resultDesc, "showtime":2000 }); $("#formId")[0].reset(); addWin.close(); }else{ new AlertWin().initfn({ "tipscon":data.resultDesc, "showtime":2000 }); } //table.load(); table.load({"pageBean.pageNo": 1,name: $.trim($("#search_name").val()),trainerTypeId:$("#search_trainerTypeId").val() } ); } }); }else{ //新增 var labels = ""; var index = 0; $(".labels").find("li").each(function(){ if(index==0){ labels += "'" + $(this).attr("data-id") + "'"; }else{ labels += ",'"+$(this).attr("data-id") + "'"; } index++; }); var param={headImg:$("#head_img").attr("data-img"),name:$("#name").val(),title:$("#title").val(),phone:$("#phone").val(),email:$("#email").val(),proField:$("#proField").val(),trainerTypeId:$("#trainerTypeId").val(),address:$("#address").val(),intro:$("#intro").val(),labels:labels }; $.ajax({ url:"${ctx}/td/trainer/insert.do", type:"get", data:param, success:function(data){ if(data.result=="true"){ new AlertWin().initfn({ "tipscon":data.resultDesc, "showtime":2000 }); $("#formId")[0].reset(); addWin.close(); }else{ new AlertWin().initfn({ "tipscon":data.resultDesc, "showtime":2000 }); } //table.load(); table.load({"pageBean.pageNo": 1,name: $.trim($("#search_name").val()),trainerTypeId:$("#search_trainerTypeId").val() } ); } }); } } });
五、Java后台代码:
/** * * @Title: uploadHeadImg * @Description: 上传头像 * @param @param file * @param @param xCoordinate * @param @param yCoordinate * @param @param width * @param @param imgName * @param @param height * @param @param request * @param @param model * @param @return * @return String * @throws */ @RequestMapping(value = "/uploadHeadImg", produces = "text/plain;charset=UTF-8") @ResponseBody public String uploadHeadImg(@RequestParam(value = "img", required = false) MultipartFile file, @RequestParam(value = "xCoordinate", required = false) Integer xCoordinate, @RequestParam(value = "yCoordinate", required = false) Integer yCoordinate, @RequestParam(value = "width", required = false) Integer width, @RequestParam(value = "imgName", required = false) String imgName, @RequestParam(value = "height", required = false) Integer height, HttpServletRequest request, ModelMap model) { String result = ""; EmpMessageRes msg = new EmpMessageRes(); //获得工程下面upload资源包路径,当然这个包是已经存在的了 String path = request.getSession().getServletContext().getRealPath("upload/trainer_picture"); //上传的图片的名称 String fileName = file.getOriginalFilename(); String newfileName = UUIDUtil.generateGUID() + fileName.substring(fileName.lastIndexOf(".")).toLowerCase(); //下面是upload路径盘符的转化 StringBuffer importPath = new StringBuffer(); String temp[] = path.split("\\\\"); for (int i = 0; i < temp.length; i++) { importPath.append(temp[i]); importPath.append("/"); } importPath.append(newfileName); //看是否存在upload包,没有则会新建一个upload包,作为资源上传的路径 File targetFile = new File(path, newfileName); if (!targetFile.exists()) { targetFile.mkdirs(); } try { //文件上传 file.transferTo(targetFile); /** *利用工具类对图片进行裁剪 */
/** //String name = "D:\\image.jpg"; if (xCoordinate != null && yCoordinate != null && width != null && height != null) { OperateImage o = new OperateImage(xCoordinate, yCoordinate, width, height); o.setSrcpath(importPath.toString()); o.setSubpath(importPath.toString()); File toCompress = new File(importPath.toString()); o.cut(); if (toCompress.length() / 1024 > 50) //将上传的图片进行压缩 ImgUtil.createIcon(importPath.toString()); }
*/
File toCompress = new File(importPath.toString());
if (toCompress.length() / 1024 > 50){
//将上传的图片进行压缩
ew ImageUtil().thumbnailImage(importPath.toString(), 360, 420, true); //180, 210
}
msg.setResult("true"); msg.setResultDesc("头像上传成功"); msg.setImgUrl(newfileName); //result = "originalFilename=" + fileName + ";imgUrl=" + msg.getImgUrl() + ";result=" + msg.getResult() + ";resultDesc=" + msg.getResultDesc(); result = msg.getImgUrl(); } catch (Exception e) { msg.setResult("false"); msg.setResultDesc("头像上传失败"); e.printStackTrace(); } if (imgName != null) { File later = new File(path, imgName); if (later != null) later.delete(); } return result; }
效果如图:
生成缩略图:
package com.dayhr.web.module.hr.td.elearn.common.util; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Arrays; import javax.imageio.ImageIO; /** * * @ClassName:ImageUtil * @Description: 生成缩略图 * @author: * @date:2015-3-31 下午3:20:27 * @version 1.0 */ public class ImageUtil { /** * * @Title: thumbnailImage * @Description: 根据图片路径生成缩略图 * @param @param imgFile 原图片路径 * @param @param w 缩略图宽 * @param @param h 缩略图高 * @param @param force 是否强制按照宽高生成缩略图(如果为false,则生成最佳比例缩略图) * @return void * @throws */ public void thumbnailImage(String imagePath, int w, int h, boolean force) { File imgFile = new File(imagePath); if (imgFile.exists()) { try { // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif] String types = Arrays.toString(ImageIO.getReaderFormatNames()); String suffix = null; // 获取图片后缀 if (imgFile.getName().indexOf(".") > -1) { suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1); } // 类型和图片后缀全部小写,然后判断后缀是否合法 if (suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0) { //System.out.println("Sorry, the image suffix is illegal. the standard image suffix is {}." + types); return; } Image img = ImageIO.read(imgFile); if (!force) { // 根据原图与要求的缩略图比例,找到最合适的缩略图比例 int width = img.getWidth(null); int height = img.getHeight(null); if ((width * 1.0) / w < (height * 1.0) / h) { if (width > w) { h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w / (width * 1.0))); //System.out.println("target image's size, width:" + w+ " height:" + h); } } else { if (height > h) { w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h / (height * 1.0))); //System.out.println("target image's size, width:" + w+ " height:" + h); } } } BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics g = bi.getGraphics(); g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null); g.dispose(); // 将图片保存在原目录 ImageIO.write(bi, suffix, imgFile); } catch (IOException e) { e.printStackTrace(); } } } // public static void main(String[] args) { // new ImageUtil().thumbnailImage("imgs/Tulips.jpg", 100, 150, false); // } }
jquery.upload.js:
var onChooseFile = ''; (function($) { var noop = function(){ return true; }; var frameCount = 0; var imgName = ''; $.uploadDefault = { url: '', fileName: 'filedata', dataType: 'json', params: {}, onSend: noop, exten: [], onComplate: noop }; $.upload = function(options) { var opts = $.extend(jQuery.uploadDefault, options); if (opts.url == '') { return; } var canSend = opts.onSend(); if (!canSend) { return; } var frameName = 'upload_frame_' + (frameCount++); var iframe = $('<iframe style="position:absolute;height:0;width:0;" name="'+frameName+'" />'); var form = $('<form method="post" style="display:none;" target="'+frameName+'" action="'+opts.url+'" name="form_'+frameName+'" enctype="multipart/form-data" />'); // 选中文件, 提交表单(开始上传) upFile = function(fileInputDOM) { imgName = fileInputDOM.value; var extension = imgName.match(/\.[^\.]+$/)[0].toLowerCase(),ontest=false; if (options.exten !== undefined) { for(var i=0;i<options.exten.length;i++){ if( extension===options.exten[i] ){ ontest=true; }; }; if(!ontest){ new Tips({ "tipscon": "格式为" + options.exten.join(",") + ",请重新选择!" }); opts.ie8&&parElement.append(oldElement) return false; }; }; form.submit(); }; var oldElement,parElement,fileInput; if(opts.ie8){ oldElement = $('#' + opts.fileElementId),parElement=oldElement.parent(); $(oldElement).appendTo(form); }else{ // form中增加数据域 var formHtml = '<input type="file" name="' + opts.fileName + '" onchange="upFile(this)">'; for (key in opts.params) { formHtml += '<input type="hidden" name="' + key + '" value="' + opts.params[key] + '">'; } form.append(formHtml); } $(document.body).append(form).append(iframe); opts.ie8&&upFile(oldElement[0]); // iframe 在提交完成之后 iframe.load(function() { var data = $(this).contents().find('body').html(); opts.onComplate(data, imgName); if(!data) return false; setTimeout(function() { opts.ie8&&parElement.append(oldElement) iframe.remove(); form.remove(); },300); }); // 文件框 if(!opts.ie8){ fileInput = $('input[type=file][name=' + opts.fileName + ']', form); fileInput.click(); } }; })(jQuery);