本文共 2424 字,大约阅读时间需要 8 分钟。
spring mvc 批量上传+文件上传
简单3步走。搞定!
上传文件成功后:
1 上传文件核心方法
public static String saveWebImgFile(MultipartFile imgFile){ String webFilePath = ""; if(imgFile.getSize() > 0 && isImage(imgFile.getContentType())){ FileOutputStream fos = null; try { byte[] b = imgFile.getBytes(); /* 构造文件路径 */ String webRoot = PathUtil.classPath(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf2 = new SimpleDateFormat("HHmmssSSS"); String datePath = sdf.format(new Date()); String datePath2 = sdf2.format(new Date()); String dirPath = webRoot + "/../../upload/img/" + datePath; File dir = new File(dirPath); if(!dir.exists()){ dir.mkdirs(); } String fileName = imgFile.getOriginalFilename(); String filePath = dirPath + "/" + datePath2 + getImgSuffix(fileName); webFilePath = "/upload/img/" + datePath + "/" + datePath2 + getImgSuffix(fileName); File file = new File(filePath); dir.setWritable(true); file.setWritable(true); fos = new FileOutputStream(file); fos.write(b); } catch (IOException e) { throw new RuntimeException("文件上传失败!" ,e); }finally{ if(fos != null){ try { fos.close(); } catch (IOException e) { throw new RuntimeException("文件上传->输出流关闭失败!!!!" ,e); } } } } return webFilePath; }2控制器代码
@RequestMapping(value = "/imgupload") public String handleFormUpload(MultipartHttpServletRequest request) throws Exception{ Listfiles = request.getFiles("file"); Map imgs = new HashMap (); for (int i = 0; i < files.size(); i++) { String webpath = FileUtil.saveWebImgFile(files.get(i)); imgs.put("img"+i, webpath); } request.setAttribute("imgs", imgs); return showImageList(request); }
3 页面代码
商品图片设置:
本文转自yjflinchong 51CTO博客,原文链接:http://blog.51cto.com/yjflinchong/1165010,如需转载请自行联系原作者