首页 > 编程语言 > 详细

SpringMVC的上传与下载

时间:2017-01-10 20:53:53      阅读:139      评论:0      收藏:0      [点我收藏+]
<style type="text/css">
        form{
            margin:0px auto; 
            border:1px solid red;
            width:500px;
            padding:20px;
        }
    </style>
  </head>
  
  <body>
   <form action="${pageContext.request.contextPath }/frist.do" method="post" enctype="multipart/form-data">
       <h1>文件上传</h1>
       文件:<input type="file" name="uploadFile"/><br/>
       文件:<input type="file" name="uploadFile"/><br/>
       文件:<input type="file" name="uploadFile"/><br/>
       <input type="submit" value="上传">
   </form>
  </body>单文件上传 

通过对文件的大小来判断是否有文件

通过文件的类型来判断是否是允许


@Controller
public class MyController {
    @RequestMapping(value="/frist.do", method=RequestMethod.POST)
    public String doFirst(HttpSession session,MultipartFile uploadFile)throws Exception{
        if(uploadFile.getSize()>0){
            String path = session.getServletContext().getRealPath("/upload");
            String fileName=uploadFile.getOriginalFilename();
            if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){
                File file = new File(path,fileName);
                uploadFile.transferTo(file);
            }
            return "welcome.jsp";
        }
        return "error.jsp";
    } applicationContext.xml配置


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        ">
 
    <!-- 配置包扫描器 -->
    <context:component-scan base-package="cn.controller"></context:component-scan>
 
 
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property><!-- 客户端发送数据的编码 -->
        <property name="maxUploadSize" value="5242880"></property><!-- 上传文件的大小 -->
        <!-- <property name="uploadTempDir" value="/upload"></property> -->
    </bean>
    <!-- mvc注解驱动 -->
    <mvc:annotation-driven />
 
</beans>web.xml


<!--?xml version="1.0" encoding="UTF-8"?-->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <!-- ================spring mvc 适配器================ -->  
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
 <!-- ================================================== --> 
    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>多文件上传(多文件上传与单文件上传配置相同下面介绍一下不同的地方)

标记为红色的字段为多文件上传 与单文件上传的区别


 @RequestMapping(value="/firstdown.do")
public String doFirst(@RequestParam MultipartFile[] uploadFile,HttpSession session)throws Exception{
    for (MultipartFile item : uploadFile) {
         
        if(item.getSize()>0){
            String path = session.getServletContext().getRealPath("/upload");
            String fileName=item.getOriginalFilename();
            if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){
                File file = new File(path,fileName);
                item.transferTo(file);
            }
            return "welcome.jsp";
        }
    }
    return "error.jsp";
}文件下载


<br> public static void download(HttpServletRequest request, 
            HttpServletResponse response, String storeName, String contentType
           ) throws Exception { 
         
        request.setCharacterEncoding("UTF-8"); 
        BufferedInputStream bis = null; 
        BufferedOutputStream bos = null; 
           String ctxPath = request.getSession().getServletContext() 
                .getRealPath(""); 
         
        String downLoadPath = ctxPath+"/uploadFile/"+ storeName; 
           long fileLength = new File(downLoadPath).length(); 
 
        response.setContentType("application/octet-stream"); 
        response.setHeader("Content-disposition", "attachment; filename=" 
                + new String(storeName.getBytes("utf-8"), "ISO8859-1"));
        
        response.setHeader("Content-Length", String.valueOf(fileLength)); 
        bis = new BufferedInputStream(new FileInputStream(downLoadPath)); 
        bos = new BufferedOutputStream(response.getOutputStream()); 
        byte[] buff = new byte[2048]; 
        int bytesRead; 
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { 
            bos.write(buff, 0, bytesRead); 
        } 
        bis.close(); 
        bos.close(); 
    } 下载直接访问控制器如:http:\\localhost:8080/springmvc/download.do

 或者通过JSP页面

<a href="./downloadFile/download" >下载</a> 

 

单文件上传 

通过对文件的大小来判断是否有文件

通过文件的类型来判断是否是允许

@Controllerpublic class MyController {
    @RequestMapping(value="/frist.do", method=RequestMethod.POST)
    public String doFirst(HttpSession session,MultipartFile uploadFile)throws Exception{
        if(uploadFile.getSize()>0){
            String path = session.getServletContext().getRealPath("/upload");
            String fileName=uploadFile.getOriginalFilename();
            if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){
                File file = new File(path,fileName);
                uploadFile.transferTo(file);
            }
            return "welcome.jsp";
        }
        return "error.jsp";
    }

 

 

 

applicationContext.xml配置

 

 

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        ">
 
    <!-- 配置包扫描器 -->
    <context:component-scan base-package="cn.controller"></context:component-scan>
 
 
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property><!-- 客户端发送数据的编码 -->
        <property name="maxUploadSize" value="5242880"></property><!-- 上传文件的大小 -->
        <!-- <property name="uploadTempDir" value="/upload"></property> -->
    </bean>
    <!-- mvc注解驱动 -->
    <mvc:annotation-driven />
 </beans>

 

 

 

web.xml

<!--?xml version="1.0" encoding="UTF-8"?--><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>
  <!-- ================spring mvc 适配器================ -->  
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list></web-app>

 

 

多文件上传(多文件上传与单文件上传配置相同下面介绍一下不同的地方)

 

标记为红色的字段为多文件上传 与单文件上传的区别

 

 @RequestMapping(value="/firstdown.do")public String doFirst(@RequestParam MultipartFile[] uploadFile,HttpSession session)throws Exception{
    for (MultipartFile item : uploadFile) {
         
        if(item.getSize()>0){
            String path = session.getServletContext().getRealPath("/upload");
            String fileName=item.getOriginalFilename();
            if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){
                File file = new File(path,fileName);
                item.transferTo(file);
            }
            return "welcome.jsp";
        }
    }
    return "error.jsp";
}

 

 

 

文件下载

 

<br> public static void download(HttpServletRequest request,
            HttpServletResponse response, String storeName, String contentType
           ) throws Exception {
        request.setCharacterEncoding("UTF-8");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
           String ctxPath = request.getSession().getServletContext()
                .getRealPath("");
        String downLoadPath = ctxPath+"/uploadFile/"+ storeName;
           long fileLength = new File(downLoadPath).length();
         response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment; filename="
                + new String(storeName.getBytes("utf-8"), "ISO8859-1"));
        response.setHeader("Content-Length", String.valueOf(fileLength));
         bis = new BufferedInputStream(new FileInputStream(downLoadPath));
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        bis.close();
        bos.close();
    }

 

 

 

 

 

下载直接访问控制器如:http:\\localhost:8080/springmvc/download.do

 

 或者通过JSP页面

 

<a href="./downloadFile/download" >下载</a> 

 

 

 

 

SpringMVC的上传与下载

原文:http://www.cnblogs.com/liu980414/p/6270499.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!