/* * 图片上传 */ @RequestMapping("/uploadFile") @ResponseBody public String uploadFile(@RequestParam(value = "imageAddr", required = false)String imageAddr,@RequestParam(value = "genre", required = false)String genre,@RequestParam(value = "uploadFile", required = false) MultipartFile uploadFile,HttpServletRequest request, HttpServletResponse response){ MapresultMap=new HashMap(); //获取当前时间 File.separator等同于/或者\\ String fileFolder = File.separator + DateUtil.getYear(new Date()) + File.separator + DateUtil.getMonth(new Date()) + File.separator + DateUtil.getDay(new Date()); String fileName =uploadFile.getOriginalFilename();//获取文件上传的名称 String newFileName=""; //获取照片类型 人员/车辆 System.out.println(fileName);
System.out.println(genre+imageAddr); try { String uploadPath="";//图片上传的目录 InputStream in = this.getClass().getResourceAsStream("/conf.properties"); Properties props = new Properties(); InputStreamReader inputStreamReader = new InputStreamReader(in, "UTF-8"); props.load(inputStreamReader); if("renyuan".equals(genre)) { uploadPath = props.getProperty("renyuan_Upload_path")+fileFolder; }else if ("cheliang".equals(genre)) { uploadPath = props.getProperty("cheliang_Upload_path")+fileFolder; } //重新命名 if(null!=fileName){ newFileName=UUID.randomUUID ()+fileName.substring (fileName.lastIndexOf (".")); } File files=new File(uploadPath,newFileName); if(!files.exists ()){ files.mkdirs (); } uploadFile.transferTo (files); resultMap.put("fileAdress",fileFolder+File.separator+newFileName); resultMap.put("imageAddr",imageAddr); resultMap.put("uploadFlag",true); } catch (Exception e) { resultMap.put("uploadFlag",false); //记日志 } String json=JSONObject.toJSONString(resultMap).toString(); writeJson(json,response); return null; } /* * 写入数据 */ private void writeJson(String json, HttpServletResponse response) { response.setContentType("application/json;charset=UTF-8"); PrintWriter out = null; try { out = response.getWriter(); out.print(json); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (null != out) { out.close(); } } }
上面是上传图片的控制层
下面是上传图片的ajax提交
function upload(path) { var form = new FormData(); var xx = $(":input[name='uploadName']").val(); var ImageName = document.getElementsByName("uploadName")[0].value; var uploadName = ImageName.name; alert(ImageName); var genre=$(":input[name='genre']").val(); var imageAddr=$(":input[name='imageAddr']").val(); //追加图片类型 人员/车辆 form.append(genre,genre); //追加回传照片地址 form.append(imageAddr,imageAddr); form.append(uploadName,ImageName); alert(path); $.ajax({ type: "POST", url:"uploadFile", contentType:'multipart/form-data', data:form, // 下面三个参数要指定,如果不指定,会报一个JQuery的错误 cache: false, contentType: false, processData: false, async: false, success: function(data) { console.log(data); if(data.uploadFlag==true){ alert("上传成功"); console.log("地址"+data.imageAddr); console.log("图片名"+data.fileAdress); alert(data.imageAddr); alert(data.fileAdress); //往input框里传值 document.getElementById(data.imageAddr).value=data.fileAdress; $("#ImgPr").attr("src",data.fileAdress); }else{ alert("上传出错"); } } }); }
多个form表单提交
图片预览可以在网上很多素材 也可以用下面发的那个 也可以上传完成后拿回传的图片路径追加给img的src显示
jQuery.fn .extend({ uploadPreview : function(opts) { var _self = this, _this = $(this); opts = jQuery.extend({ Img : "ImgPr", Width : 100, Height : 100, ImgType : [ "gif", "jpeg", "jpg", "bmp", "png" ], Callback : function() { } }, opts || {}); _self.getObjectURL = function(file) { var url = null; if (window.createObjectURL != undefined) { url = window.createObjectURL(file) } else if (window.URL != undefined) { url = window.URL.createObjectURL(file) } else if (window.webkitURL != undefined) { url = window.webkitURL.createObjectURL(file) } return url }; _this .change(function() { if (this.value) { if (!RegExp( "\.(" + opts.ImgType.join("|") + ")$", "i").test( this.value.toLowerCase())) { alert("选择文件错误,图片类型必须是" + opts.ImgType.join(",") + "中的一种"); this.value = ""; return false } //高版本Jquey使用 if ($.support.leadingWhitespace) if ($.support.leadingWhitespace) { //低版本jquery中使用$.browser.msie console .log(_self .getObjectURL(this.files[0])); try { _this .parent('div') .find("." + opts.Img) .attr( 'src', _self .getObjectURL(this.files[0])); } catch (e) { var src = ""; var obj = _this.parent('div') .find("." + opts.Img); var div = obj.parent("div")[0]; _self.select(); if (top != self) { window.parent.document.body .focus() } else { _self.blur() } src = document.selection .createRange().text; document.selection.empty(); obj.hide(); obj .parent("div") .css( { 'filter' : 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)', 'width' : opts.Width + 'px', 'height' : opts.Height + 'px' }); div.filters .item("DXImageTransform.Microsoft.AlphaImageLoader").src = src } } else { _this .parent('div') .find("." + opts.Img) .attr( 'src', _self .getObjectURL(this.files[0])) } opts.Callback() } }) } }); $(".up").click(function() { $(this).uploadPreview({ Img : "ImgPr" }); })