SpringMVC-文件上传和下载

SpringMVC利用Apache Commons
FileUpload技术实现了一个MultipartResolver实现类:CommonsMultipartResolver,下面简单示例用它进行文件的上传与下载。

文件上传

1、导包
需要的jar包可以从maven导入,也可以直接去maven repository 下载,需要Apache Commons FileUpload组件的包:
需要的JAR包
2、编写一个简单的文件上传form表单,记住一定要将enctype属性设为enctype="multipart/form-data"

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
    <h2>文件上传</h2>
    <form name="fileForm" action="${pageContext.request.getContextPath()}/upload" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td>文件描述:</td>
                <td> <input type="text" name="des" placeholder="请输入文件描述" /> </td>
            </tr>

            <tr>
                <td>请选择文件:</td>
                <td>
                    <input type="file" name="file" />
                </td>
            </tr>
        </table>
        <input type="submit" value="上传" />
    </form>
</body>
</html>

3、编写后端接口:

//上传的文件会自动绑定到MultipartFile中
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(
            HttpServletRequest request,
            @RequestParam("des")String des,
            @RequestParam("file")MultipartFile file,
            Model model
            )throws Exception{
        System.out.println(des);
        //如果文件不为空,写入上传路径
        if (!file.isEmpty()){
            //服务器路径
            String path = request.getServletContext().getRealPath("/images/");
            //文件名
            String fileName = file.getOriginalFilename();
            File filepath = new File(path,fileName);
            //判断要保存的路径(path)是否存在
            if (!filepath.getParentFile().exists()){
                //不存在则创建文件夹
                filepath.getParentFile().mkdirs();
            }
            // 将上传的文件保存到服务器的目标文件中
            file.transferTo(new File(path+File.separator+fileName));
            model.addAttribute("img",file);
            return "success";
        }
        return "error";
    }

原理
4、spring配置文件,配置文件上传:

<!--    配置文件上传-->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<!--        上传文件大小上限,单位为字节(10MB)-->
        <property name="maxUploadSize">
            <value>10485760</value>
        </property>
<!--        请求的编码格式,必须和JSP的pageEncoding属性一致,以便正确读取表单内容-->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

5、测试:
文件上传
点击“上传”,文件会被上传并保存到所在项目(发布文件夹)下的images文件夹下面:
项目文件夹

文件下载

原理
直接上Controller:

@RequestMapping(value = "/download")
    public ResponseEntity<byte[]> download(@RequestParam("filename") String filename, HttpServletRequest request, Model model) throws IOException {
        //下载文件的路径
        String path = request.getServletContext().getRealPath("/images/");
        File file = new File(path+File.separator+filename);
        HttpHeaders httpHeaders = new HttpHeaders();
        // 下载显示的文件名,解决中文乱码问题
        String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        // 通知浏览器以 attachment(下载方式)打开文件
        httpHeaders.setContentDispositionFormData("attachment",downloadFileName);
        // 以二进制流数据下载(最常见的文件下载方式)
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.CREATED);
    }

success.jsp(文件下载页面):

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件下载</title>
</head>
<body>
    <h2>文件下载</h2>
    <hr />
    <a href="${pageContext.request.getContextPath()}/download?filename=${img.originalFilename}">${img.originalFilename}</a>
</body>
</html>

测试:
文件下载界面

附完整代码

结构(开发工具:IDEA):
在这里插入图片描述
web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_4_0.xsd"
           version="4.0">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.gongsir.test" />

    <mvc:default-servlet-handler />
    <mvc:annotation-driven />

<!--    配置文件上传-->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<!--        上传文件大小上限,单位为字节(10MB)-->
        <property name="maxUploadSize">
            <value>10485760</value>
        </property>
<!--        请求的编码格式,必须和JSP的pageEncoding属性一致,以便正确读取表单内容-->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
        <property name="prefix">
            <value>/WEB-INF/content/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

FileController.java:

package com.gongsir.test.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class FileController {

    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public String api(@PathVariable String name){
        return name;
    }

    //上传的文件会自动绑定到MultipartFile中
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(
            HttpServletRequest request,
            @RequestParam("des")String des,
            @RequestParam("file")MultipartFile file,
            Model model
            )throws Exception{
        System.out.println(des);
        //如果文件不为空,写入上传路径
        if (!file.isEmpty()){
            //服务器路径
            String path = request.getServletContext().getRealPath("/images/");
            //文件名
            String fileName = file.getOriginalFilename();
            File filepath = new File(path,fileName);
            //判断要保存的路径(path)是否存在
            if (!filepath.getParentFile().exists()){
                //不存在则创建文件夹
                filepath.getParentFile().mkdirs();
            }
            // 将上传的文件保存到服务器的目标文件中
            file.transferTo(new File(path+File.separator+fileName));
            model.addAttribute("img",file);
            return "success";
        }
        return "error";
    }

    @RequestMapping(value = "/download")
    public ResponseEntity<byte[]> download(@RequestParam("filename") String filename, HttpServletRequest request, Model model) throws IOException {
        //下载文件的路径
        String path = request.getServletContext().getRealPath("/images/");
        File file = new File(path+File.separator+filename);
        HttpHeaders httpHeaders = new HttpHeaders();
        // 下载显示的文件名,解决中文乱码问题
        String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        // 通知浏览器以 attachment(下载方式)打开文件
        httpHeaders.setContentDispositionFormData("attachment",downloadFileName);
        // 以二进制流数据下载(最常见的文件下载方式)
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.CREATED);
    }
}

发布了19 篇原创文章 · 获赞 24 · 访问量 4632

猜你喜欢

转载自blog.csdn.net/qq_41337581/article/details/98872905