SpringMVC:文件上传和下载

文件上传和下载

项目结构

jar包

springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
      http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.2.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

    <!--
        可以扫描controller、service、...
        这里让扫描controller,指定controller的包
     -->
    <context:component-scan base-package="org.haiwen.controller"></context:component-scan>

    <!-- 开启spring对mvc的注解支持(全注解一定要配置) -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 解决Controller返回json中文乱码问题 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 静态资源放行 -->
    <mvc:default-servlet-handler />

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>10000000000</value> <!-- 以字节byte为单位 -->
        </property>
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

    <!-- 配置SpringMVC的核心控制器DispatcherServlet(负责所有请求的公共功能,然后在分发给具体的控制器(我们编写的控制器),完成业务逻辑,响应视图。) -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
            服务器在启动的时候,去加载springmvc的配置文件
            如果不配置就默认去WEB-INF文件夹下找:<servlet-name>-servlet.xml的配置(这种方式需要拷贝配置文件到WEB-INF)
         -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!-- Servlet容器启动的时候就进行初始化 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!-- 请求的入口,所有请求都会经过DispatcherServlet处理   /:支持RESTful风格 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!-- 配置编码过滤器 ==>目的:解决SpringMVC post提交数据时的乱码问题  -->
    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

前端页面index.jsp,上传文件注意事项:

①post提交数据

②form表单 --> enctype属性为:multipart/form-data

③使用上传文件的file标签

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
<h3>文件上传</h3>
<form action="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data">
    用户名:<input type="text" name="username"><br/>
    文件上传:<input type="file" name="image"><br/>
    <input type="submit" value="提交"><br/>
</form>

<h3>文件下载</h3>
<a href="${pageContext.request.contextPath }/download?filename=1.jpg">下载1</a>
<a href="${pageContext.request.contextPath }/download2?filename=1.jpg">下载2</a>
</body>
</html>

文件上传功能类UploadController.java

/**
 * 上传文件:
 * 使用MultipartFile类型接收前台上传的文件数据
 * 接收数据时要指定接收方式-->RequestMethod.POST
 */
@Controller
public class UploadController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody //不写会默认返回当前路径!!
    public void upload(String username, MultipartFile image, HttpServletRequest req) throws Exception, IOException {
        System.out.println("username:" + username);
        /* 接收文件数据 */
        System.out.println(image.getContentType());//  image/jpeg   获取上传文件的类型
        System.out.println(image.getName());//image  获取file标签的name属性  <input type="file" name="image" >
        System.out.println(image.getOriginalFilename());//1.jpg   获取上传文件的名称

        //获取到上传的文件数据
        String contentType = image.getContentType();
        //判断上传文件是否为图片
        if (contentType == null || !contentType.startsWith("image/")) {
            System.out.println("===不属于图片类型...===");
            return;
        }

        //动态获取上传文件夹的路径
        ServletContext context = req.getServletContext();
        String realPath = context.getRealPath("/upload");//获取本地存储位置的绝对路径

        String filename = image.getOriginalFilename();//获取上传时的文件名称
        filename = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(filename);//创建一个新的文件名称    getExtension(name):获取文件后缀名

        File f = new File(realPath, filename);
        image.transferTo(f);//将上传的文件存储到指定位置
    }
}

文件下载功能类DownloadController.java

@Controller
public class DownloadController {
    /*
     * 下载方式一:
     * ①获取前台要下载的文件名称
     * ②设置响应类型
     * ③设置下载页显示的文件名
     * ④获取下载文件夹的绝对路径和文件名合并为File类型
     * ⑤将文件复制到浏览器
     */
    @RequestMapping("/download")
    @ResponseBody
    public void download(HttpServletRequest req, HttpServletResponse resp, String filename) throws Exception {
        String realPath = req.getServletContext().getRealPath("/download");//获取下载文件的路径
        File file = new File(realPath, filename);//把下载文件构成一个文件处理   filename:前台传过来的文件名称

        //设置响应类型  ==》 告诉浏览器当前是下载操作,我要下载东西
        resp.setContentType("application/x-msdownload");
        //设置下载时文件的显示类型(即文件名称-后缀)   ex:txt为文本类型
        resp.setHeader("Content-Disposition", "attachment;filename=" + filename);

        //下载文件:将一个路径下的文件数据转到一个输出流中,也就是把服务器文件通过流写(复制)到浏览器端
        Files.copy(file.toPath(), resp.getOutputStream());//Files.copy(要下载的文件的路径,响应的输出流)
    }

    /*
     * 下载方式二:Spring框架技术
     */
    @RequestMapping(value = "/download2", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(HttpServletRequest request, String filename) throws IOException {
        String realPath = request.getServletContext().getRealPath("/download");//获取下载文件的路径
        File file = new File(realPath, filename);//把下载文件构成一个文件处理   filename:前台传过来的文件名称

        HttpHeaders headers = new HttpHeaders();//设置头信息
        String downloadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");//设置响应的文件名

        headers.setContentDispositionFormData("attachment", downloadFileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // MediaType:互联网媒介类型 contentType:具体请求中的媒体类型信息
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }
}

测试

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值