SpringMVC文件上传实现

本文详细介绍了使用SpringMVC实现文件上传的方法,包括表单的enctype设置、配置MultipartResolver处理器、处理上传文件限制及异常、上传文件的表单页面及提示页面设计,以及核心UploadController类的实现。

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

SpringMVC文件上传实现

SpringMVC(注解)上传文件需要注意的几个地方:
1、form的enctype="multipart/form-data",这个是上传文件必须的
2、applicationContext.xml配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> 
<bean id= "multipartResolver"  class = "org.springframework.web.multipart.commons.CommonsMultipartResolver"
     <property name= "defaultEncoding"  value= "UTF-8" /> 
     <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> 
     <property name= "maxUploadSize"  value= "200000" />
     <!-- 最大内存大小 ( 10240 )--> 
     <property name= "maxInMemorySize"  value= "40960"  />
</bean> 
   
<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> 
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --> 
<bean id= "exceptionResolver"  class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"
     <property name= "exceptionMappings"
         <props> 
             <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 --> 
             <prop key= "org.springframework.web.multipart.MaxUploadSizeExceededException" >error_fileupload</prop> 
         </props> 
     </property> 
</bean>

  

用于上传的表单页面/WEB-INF/jsp/upload.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<! DOCTYPE  html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
< html >
     < head >
         < script  type="text/javascript" src="../js/jquery-1.7.1.min.js"></ script >
         < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8">
         < title >上传图片</ title >
     </ head >
     < body >
         < form  action="<%=request.getContextPath()%>/upload/filesUpload" method="POST" enctype="multipart/form-data"> 
             yourfile: < input  type="file" name="myfiles"/>< br /> 
             yourfile: < input  type="file" name="myfiles"/>< br /> 
             < input  type="submit" value="上传图片"/> 
         </ form
     </ body >
</ html >

  

上传文件内容过大时的提示页面/WEB-INF/jsp/error_fileupload.jsp

1
2
<%@ page language="java" pageEncoding="UTF-8"%>
< h1 >文件过大,请重新选择</ h1 >

  

上传文件的核心UploadController类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package  com.ljq.web.controller.annotation;
 
import  java.io.File;
 
import  javax.servlet.http.HttpServletRequest;
 
import  org.springframework.stereotype.Controller;
import  org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.bind.annotation.RequestParam;
import  org.springframework.web.multipart.MultipartFile;
 
/**
  * 上传图片
  *
  * @author Administrator
  *
  */
@Controller
@RequestMapping ( "/upload" )
public  class  UploadController {
 
     @RequestMapping ( "/toUpload" )
     public  String toUpload() {
         return  "/upload" ;
     }
 
     /***
      * 保存文件
      *
      * @param file
      * @return
      */
     private  boolean  saveFile(HttpServletRequest request, MultipartFile file) {
         // 判断文件是否为空
         if  (!file.isEmpty()) {
             try  {
                 // 保存的文件路径(如果用的是Tomcat服务器,文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中  )
                 String filePath = request.getSession().getServletContext()
                     .getRealPath( "/" ) +  "upload/"  + file.getOriginalFilename();
                 File saveDir =  new  File(filePath);
                 if  (!saveDir.getParentFile().exists())
                     saveDir.getParentFile().mkdirs();
                 
                 // 转存文件
                 file.transferTo(saveDir);
                 return  true ;
             catch  (Exception e) {
                 e.printStackTrace();
             }
         }
         return  false ;
     }
 
     /**
      * 上传图片
      *
      * @param files
      * @param request
      * @return
      */
     @RequestMapping ( "/filesUpload" )
     public  String filesUpload( @RequestParam ( "myfiles" ) MultipartFile[] files,
             HttpServletRequest request) {
         if  (files !=  null  && files.length >  0 ) {
             for  ( int  i =  0 ; i < files.length; i++) {
                 MultipartFile file = files[i];
                 // 保存文件
                 saveFile(request, file);
             }
         }
         
         // 重定向
         return  "redirect:/upload/toUpload" ;
     }
 
}

  

到此文件上传开发就结束了。

MultipartFile类常用的一些方法:
String getContentType() //获取文件MIME类型
InputStream getInputStream() //返回文件流
String getName() //获取表单中文件组件的名字
String getOriginalFilename() //获取上传文件的原名
long getSize() //获取文件的字节大小,单位byte
boolean isEmpty() //是否为空
void transferTo(File dest) //保存到一个目标文件中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值