Spring mvc文件上传与下载

文件上传

SpringMVC实现文件上传,需要再添加两个jar包。一个是文件上传的jar包,一个是其所依赖的IO包。这两个jar包,均在Spring支持库的org.apache.commons中。

单文件上传

jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <style type="text/css">
       form{
         margin:0px auto;
         border:1px solid red;
         width:500px;
         padding:20px;
       }
    </style>
    <title></title>
  </head>

  <body>
    <form action="${pageContext.request.contextPath }/first.do" method="post" enctype="multipart/form-data">
    <h1>文件上传</h1>
                 文件:<input type="file" name="uploadFile"/><br/>
       <input type="submit" value="上传"/>
    </form>
  </body>
</html>

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

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

@Controller
public class MyController {
    @RequestMapping(value="/frist.do", method=RequestMethod.POST)
    public String doFirst(HttpSession session,MultipartFile uploadFile)throws Exception{
        if(uploadFile.getSize()>0){
            //02.获取前半部分路径,jiangWebRoot下一个名称为images文件夹  转换成绝对路径
            String path = session.getServletContext().getRealPath("/upload");
            //01.获取文件名作为保存到服务器的文件名称
            String fileName=uploadFile.getOriginalFilename();
            if(fileName.endsWith(".jpg")||fileName.endsWith(".JPG")){
                //03.路径拼接
                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>	

  <!-- 编码过滤器 -->
  <filter>
    <filter-name>CharacterEncoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- 配置中央调度器 -->
  <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>
    <!-- TOmcat启动的时候,Servlet对象就存储到内存 正整数 -->
    <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="/first.do")
<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();
    }

  JSP页面

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

  

时间: 2024-08-05 10:53:19

Spring mvc文件上传与下载的相关文章

Spring MVC文件上传和下载

在Spring MVC中有两种实现上传文件的办法,第一种是Servlet3.0以下的版本通过commons-fileupload与commons-io完成的通用上传,第二种是Servlet3.0以上的版本的Spring内置标准上传,不需借助第3方组件.通用上传也兼容Servlet3.0以上的版本 Servlet3.0以下的通过commons-fileupload上传 1.添加上传依赖包 一个是文件上传的jar包,一个是其所依赖的IO包.这两个jar包,均在Spring支持库的org.apache

Spring MVC 文件上传与下载2及分页功能

Service 方法public List<Map<String,Object>> handleMultipartRequest(String fileGuid, MultipartRequest request, HttpServletRequest httpServletRequest) throws Exception {List<Map<String, Object>> uploadFileList=new ArrayList<Map<S

Spring MVC文件上传出现错误:Required MultipartFile parameter &#39;file&#39; is not present

1.配置文件上传的解析器 首先需要在spring mvc的配置文件中(注意是spring mvc的配置文件而不是spring的配置文件:applicationContext.xml)配置: springmvc-config.xml <!-- 文件上传bean--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartReso

spring mvc文件上传方法

spring mvc上传功能很强大. spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype="multipart/form-data" 这个是上传文件必须的2.applicationContext.xml中 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolv

Spring mvc 文件上传到文件夹(转载+心得)

spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationContext.xml中 <bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”/> 关于文件上传的配置不能少 applicationContext.xml

Spring MVC文件上传下载(转载)

原文地址: http://www.cnblogs.com/WJ-163/p/6269409.html 上传参考 http://www.cnblogs.com/lonecloud/p/5990060.html 下载参考 一.关键步骤 ①引入核心JAR文件 SpringMVC实现文件上传,需要再添加两个jar包.一个是文件上传的jar包,一个是其所依赖的IO包.这两个jar包,均在Spring支持库的org.apache.commons中. ②书写控制器方法 applicationContext.x

spring mvc文件上传下载

web xml springMvc 注册添加 <multipart-config> <max-file-size>20848820</max-file-size> <max-request-size>418018841</max-request-size> <file-size-threshold>1048576</file-size-threshold> </multipart-config> springM

spring mvc文件上传

1.配置spring mvc配置文件 <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" valu

Strut2 和Spring MVC 文件上传对比

在Java领域中,有两个常用的文件上传项目:一个是Apache组织Jakarta的Common-FileUpload组件 (http://commons.apache.org/proper/commons-fileupload/),另一个是Oreilly组织的COS框架的 (http://www.servlets.com/cos). 1.Struts2的文件上传 Struts2本身并没提供上传的组件,我们可以通过调用上传框架来实现文件的上传,struts2默认是jakarta作为其文件上传的解析