SpringMVC实现多文件(批量)上传

本文介绍如何使用SpringMVC实现多文件上传功能,包括必要的依赖包、控制器代码、前端表单设置及配置文件说明。

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

1.springMVC实现多文件上传需要的包如图2.webroot下的结构如图所示

3.java代码:

 1 package cn.lxc.controller;
 2 
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.io.OutputStream;
 8 
 9 import javax.servlet.http.HttpServletRequest;
10 
11 import org.springframework.stereotype.Controller;
12 import org.springframework.web.bind.annotation.RequestMapping;
13 import org.springframework.web.bind.annotation.RequestParam;
14 import org.springframework.web.multipart.commons.CommonsMultipartFile;
15 
16 @Controller
17 public class UploadController {
18     @RequestMapping("/upload.do")
19     public String upload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest req){
20         String path= req.getSession().getServletContext().getRealPath("/");
21         System.out.println(path);
22         String fileName=file.getOriginalFilename();
23         try {
24             InputStream is = file.getInputStream();
25             OutputStream os = new FileOutputStream(new File(path,fileName));
26             int len=0;
27             byte[] buffer = new byte[400];
28             while((len=is.read(buffer))!=-1){ //len为读取数据的字节长度
29                 os.write(buffer, 0, len); //三个参数分别为输出的字节数组、数据起始偏移量,输出字节长度
30             }
31             os.close();
32             is.close();
33         
34         } catch (IOException e) {
35             e.printStackTrace();
36         }
37         return "redirect:/index.jsp";
38     }
39 }

4.jsp代码 

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     <title>My JSP 'index.jsp' starting page</title>
12   </head>
13   <body>
14    <form action="upload.do" method="post" enctype="multipart/form-data">
15    file1:<input type="file" name="file"/>
16          <input type="submit" value="上传"/> 
17    </form>
18   </body>
19 </html>

5.springmvc-servlet.xml配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="
 7         http://www.springframework.org/schema/beans
 8         http://www.springframework.org/schema/beans/spring-beans.xsd
 9         http://www.springframework.org/schema/context
10         http://www.springframework.org/schema/context/spring-context.xsd">
11     <!-- 适配器 使用注解 -->
12     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> 
13     <!-- 渲染器 -->
14     <bean id="viewResolver"
15         class="org.springframework.web.servlet.view.UrlBasedViewResolver">
16         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
17         <property name="prefix" value="/WEB-INF/jsp/"/>
18         <property name="suffix" value=".jsp"/>
19     </bean>
20     <!-- 文件上传配置 -->
21     <bean id="multipartResolver"  
22         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
23         <property name="defaultEncoding" value="utf-8"></property>   
24         <property name="maxUploadSize" value="104857600"></property>  
25         <property name="maxInMemorySize" value="40960"></property>  
26     </bean>
27     <!-- 扫描注解包 -->
28     <context:component-scan base-package="cn.lxc.controller" />  
29 </beans>

6.web.xml配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 3   <servlet>
 4     <servlet-name>springmvc</servlet-name>
 5     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 6     <load-on-startup>1</load-on-startup>
 7   </servlet>
 8   <servlet-mapping>
 9     <servlet-name>springmvc</servlet-name>
10     <url-pattern>*.do</url-pattern>
11   </servlet-mapping>
12 </web-app>

 

转载于:https://www.cnblogs.com/lxcmyf/p/5472907.html

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、付费专栏及课程。

余额充值