在后台 需要一个上传的工具类:
@Controller @RequestMapping(value="/upload") public class UploadUtil { @ResponseBody @RequestMapping(value="/upload.do") public String upload2(HttpServletRequest request, HttpServletResponse response) throws Exception{ //创建一个通用的多部分解析器 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //判断request是否有文件需要上传 if(multipartResolver.isMultipart(request)){ //转换成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; String pth = null; List<MultipartFile> fileList = multiRequest.getFiles("file"); for (MultipartFile mf : fileList) { if(!mf.isEmpty()){ //取得当前上传文件的名称 String myFileName = mf.getOriginalFilename(); //如果名称不为"",说明该文件存在,否则说明文件不存在。 if(myFileName.trim()!=""){ System.out.println(myFileName); //重命名上传后的文件 String filename = "upload"+mf.getOriginalFilename(); String type=filename.substring(filename.lastIndexOf(".")+1); if(type.equals("jpg")||type.equals("png")){ Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss"); String da = format.format(date); String newName = da+ getRandomString2(4) + "." + type; //定义上传路劲 String path = request.getSession().getServletContext().getRealPath("/uploadImg"); String reelPath = path+"/"+newName; pth="/uploadImg/"+newName; File localFile = new File(path); if (!localFile.exists()) { // 判断文件夹是否存在,不存在则新建 localFile.mkdirs(); } File realFile = new File(reelPath); mf.transferTo(realFile); return pth; }else{ return "2";//文件类型只能是JPG、PNG } }else{ return "1";//文件不存在 } } } return null; }else{ return "0";//没有文件需要上传 } } public static String getRandomString2(int length){ Random random=new Random(); StringBuffer sb=new StringBuffer(); for(int i=0;i<length;i++){ int number=random.nextInt(3); long result=0; switch(number){ case 0: result=Math.round(Math.random()*25+65); sb.append(String.valueOf((char)result)); break; case 1: result=Math.round(Math.random()*25+97); sb.append(String.valueOf((char)result)); break; case 2: sb.append(String.valueOf(new Random().nextInt(10))); break; } } return sb.toString(); } }
在JSP页面上
<form id="imgForm" enctype="multipart/form-data" > <div class="form-group"> <div style="display: inline-block"><label for="upfile">上传阶段图片:</label></div>
<img id="preview" src="${ctx}/weixin/images/upload/upload_img.png"><div style="display: inline-block"><input type="file" name="file" id="upfile" multiple="multiple"/></div> <div style="text-align: center; margin: 10px 0"><button id="setImg" type="button" class="btn btn-primary" >开始上传</button></div> </div></form>
最后一个AJAX的脚本
//上传图片 $("#wrapper").on("click", "#setImg", function() { var $file = $("#upfile"); var fileObj = $file[0]; var windowURL = window.URL || window.webkitURL; var dataURL; var $img = $("#preview"); if (fileObj && fileObj.files && fileObj.files[0]) { dataURL = windowURL.createObjectURL(fileObj.files[0]); $img.css("width", "100%"); $img.css("height", "100%"); $img.attr('src', dataURL); var formData = new FormData($("#imgForm")[0]); $.ajax({ url: "/agrovideo/upload/upload.do", type: 'post', data: formData, cache: false, processData: false, contentType: false, success: function(data) { if (data != null && data != '') { if (data == "0") { $.MsgBox.Alert("没有文件需要上传"); } else if (data == "1") { $.MsgBox.Alert("文件不存在"); } else if (data == "2") { $.MsgBox.Alert("文件类型只能是JPG、PNG"); } else { $.MsgBox.Alert("上传成功"); $("#imgPath").val(data); } } else { $.MsgBox.Alert("上传失败"); } }, error: function() { $.MsgBox.Alert("上传失败"); } }); } });