spring mvc 批量上传+文件上传

本文介绍如何使用Spring MVC实现文件批量上传功能,包括核心方法实现、控制器代码及页面展示,采用简单三步走策略解决文件上传问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring mvc 批量上传+文件上传

简单3步走。搞定!

上传文件成功后:



1 上传文件核心方法

  1. public static String saveWebImgFile(MultipartFile imgFile){  
  2.         String webFilePath = "";  
  3.         if(imgFile.getSize() > 0 && isImage(imgFile.getContentType())){  
  4.             FileOutputStream fos = null;  
  5.             try {  
  6.                 byte[] b = imgFile.getBytes();  
  7.                 /* 构造文件路径 */  
  8.                 String webRoot = PathUtil.classPath();  
  9.                 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");  
  10.                 SimpleDateFormat sdf2 = new SimpleDateFormat("HHmmssSSS");  
  11.                 String datePath = sdf.format(new Date());  
  12.                 String datePath2 = sdf2.format(new Date());  
  13.                 String dirPath = webRoot + "/../../upload/img/" + datePath;  
  14.                 File dir = new File(dirPath);  
  15.                 if(!dir.exists()){  
  16.                     dir.mkdirs();  
  17.                 }  
  18.                 String fileName = imgFile.getOriginalFilename();  
  19.                 String filePath = dirPath + "/" + datePath2 + getImgSuffix(fileName);  
  20.                 webFilePath = "/upload/img/" + datePath + "/" + datePath2 + getImgSuffix(fileName);  
  21.                 File file = new File(filePath);  
  22.                   
  23.                 dir.setWritable(true);  
  24.                 file.setWritable(true);  
  25.                   
  26.                 fos = new FileOutputStream(file);  
  27.                 fos.write(b);  
  28.                   
  29.             } catch (IOException e) {  
  30.                 throw new RuntimeException("文件上传失败!" ,e);  
  31.             }finally{  
  32.                 if(fos != null){  
  33.                     try {  
  34.                         fos.close();  
  35.                     } catch (IOException e) {  
  36.                         throw new RuntimeException("文件上传->输出流关闭失败!!!!" ,e);  
  37.                     }  
  38.                 }  
  39.             }  
  40.         }  
  41.           
  42.         return webFilePath;  
  43.     }  



2控制器代码

  1. @RequestMapping(value = "/imgupload")  
  2.      public String handleFormUpload(MultipartHttpServletRequest request) throws Exception{    
  3.          List<MultipartFile> files = request.getFiles("file");  
  4.          Map<String, String> imgs = new HashMap<String, String>();  
  5.          for (int i = 0; i < files.size(); i++) {  
  6.             String webpath = FileUtil.saveWebImgFile(files.get(i));  
  7.             imgs.put("img"+i, webpath);  
  8.         }  
  9.         request.setAttribute("imgs", imgs);  
  10.         return showImageList(request);  
  11.      }  



3 页面代码

  1. <body>  
  2.     商品图片设置:  
  3.     <form method="post"  enctype="multipart/form-data" action="product/imgupload" name="imagefrm">  
  4.     <table>  
  5.         <tr>  
  6.         <td>商品大图:默认宽度600px,高度600px</td>  
  7.         </tr>  
  8.         <tr>  
  9.         <td><input type="file" name="file"/><c:if test="${imgs.img0!=null&&imgs.img0!=''}"><img src="<%=basePath %>${imgs.img0 }" style="width:40;height:40px;"/></c:if></td>  
  10.         </tr>  
  11.         <tr>  
  12.         <td>添加多角度图片:默认宽度50px,高度50px</td>  
  13.         </tr>  
  14.         <tr>  
  15.         <td><input type="file" name="file"/><c:if test="${imgs.img1!=null&&imgs.img1!=''}"><img src="<%=basePath %>${imgs.img1 }" style="width:40;height:40px;"/></c:if></td>  
  16.         </tr>  
  17.         <tr>  
  18.         <td><input type="file" name="file"/><c:if test="${imgs.img2!=null&&imgs.img2!=''}"><img src="<%=basePath %>${imgs.img2 }" style="width:40;height:40px;"/></c:if></td>  
  19.         </tr>  
  20.         <tr>  
  21.         <td><input type="file" name="file"/><c:if test="${imgs.img3!=null&&imgs.img3!=''}"><img src="<%=basePath %>${imgs.img3 }" style="width:40;height:40px;"/></c:if></td>  
  22.         </tr>  
  23.         <tr>  
  24.         <td><input type="file" name="file"/><c:if test="${imgs.img4!=null&&imgs.img4!=''}"><img src="<%=basePath %>${imgs.img4 }" style="width:40;height:40px;"/></c:if></td>  
  25.         </tr>  
  26.         <tr>  
  27.         <td><input type="submit" value="上传所有图片"/></td>   
  28.         </tr>  
  29.     </table>  
  30. </form>  
  31.  </body>  
java 基于springMVC多图片上传,MySQL源码 @Controller @RequestMapping("/upload") public class UploadFileController { @Autowired private UploadFileService uploadFileService; @RequestMapping("/upfile") public String upload(HttpServletRequest request, @RequestParam("designation") String designation, @RequestParam("remark") String remark, //@RequestParam("file") String file, Model model)throws Exception { String str = designation; String[] st=str.split(","); //以逗号为分隔符进行截取 String re = remark; String[] stre = re.split(","); UploadFile uploadFile = new UploadFile(); //转成文件上传请求 MultipartHttpServletRequest murequest = (MultipartHttpServletRequest)request; //在文件上传请求中获取文件,根据file的name List files = murequest.getFiles("image"); if( files !=null && files.size()>0) { for(int i=0; i<files.size(); i++) { String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase()+"_"; String filename = files.get(i).getOriginalFilename(); //System.out.println("filename="+filename); int hCode =filename.hashCode(); String hex = Integer.toHexString(hCode); String mkdir = hex.charAt(0)+"\\"+hex.charAt(1)+"\\"; String path = request.getServletContext().getRealPath("/images/")+mkdir; //System.out.println("path="+path); File filepath = new File(path,filename); if(!filepath.getParentFile().exists()) { filepath.getParentFile().mkdirs(); } //将上传文件保存到目标文件中 files.get(i).transferTo(new File(path+File.separator+filename)); //获取数据库存储路径 String root = request.getContextPath(); String mkdirsql = hex.charAt(0)+"/"+hex.charAt(1)+"/"; String sqlpath = root+"/images/"+mkdirsql+filename; String imgpath = sqlpath; //图片保存到数据库的路径 uploadFile.setDesignation(st[i]); uploadFile.setRemark(stre[i]); uploadFile.setFile(filename); uploadFile.setImgpath(sqlpath); uploadFileService.addUploadFile(uploadFile); } return "success"; } return "404"; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值