利用diyUpload做多图片上传及预览
程序员文章站
2022-03-15 14:55:01
...
需求:
1.ajax上传多个图片
2.图片预览
实现:
1.引入附件的js
2.html页面:
<div id="test" > </div> <script type="text/javascript"> $('#test').diyUpload({ url:'${basePath}upload/img', success:function( data ) { console.info( data ); }, error:function( err ) { console.info( err ); } }); </script>
2.java上传类代码:
@Controller @RequestMapping("upload") public class UploadController { private String processImg(HttpServletRequest request, String imageDir) throws Exception { String uuid = CommonUtils.getUUID(); request.setCharacterEncoding("UTF-8"); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8")); } else { System.out.println("上传文件的大小:" + item.getSize()); System.out.println("上传文件的类型:" + item.getContentType()); System.out.println("上传文件的名称:" + item.getName()); FileUtils.forceMkdir(new File(imageDir)); String file = imageDir + File.separator + uuid + "." + FilenameUtils.getExtension(item.getName()); item.write(new File(file)); return uuid + "." + FilenameUtils.getExtension(item.getName()); } } return uuid; } @RequestMapping(value = "/img", method = RequestMethod.POST) @ResponseBody public UploadResVo img(HttpServletRequest request) throws Exception { if (!isLogin(request)) { throw new RuntimeException(ExceptionMsg.UI_NOPERMISSION); } CommonProperties commonProperties = RequestContextUtils .getWebApplicationContext(request).getBean( "com.eqiurong.mp.vo.CommonProperties", CommonProperties.class); String imageDir = commonProperties.baseRealDir + File.separator + commonProperties.uploadDir + File.separator; UploadResVo resVo = new UploadResVo(); MsgVo msg = new MsgVo(); String file = processImg(request, imageDir); msg.setId(file); msg.setLocalname(file); msg.setUrl(commonProperties.basePath + commonProperties.uploadDir + File.separator + file); resVo.setMsg(msg); return resVo; } }