SpringMVC学习(8)—— 文件上传和下载

一. 文件下载

使用ResponseEntity实现下载文件的功能,可以下载图片、文档、音频等各种类型

package com.mvc.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class FileUpAndDownController {
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/fileDown")
    public ResponseEntity<byte[]> testFileDown(HttpSession session) throws IOException {
        //获取要下载的文件
        String downloadFile = "/static/img/school.jpg";

        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取文件在服务器中的真实路径
        String realPath = servletContext.getRealPath(downloadFile);

        //创建输入流
        InputStream is = new FileInputStream(realPath);
        //创建字节数组,获取当前文件中所有的字节数
        byte[] bytes = new byte[is.available()];
        //将流读到字节数组中
        is.read(bytes);


        //创建HttpHeaders对象用于设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        //设置响应头信息,Content-Disposition响应头表示收到的数据怎么处理(固定),attachment表示下载使用(固定),filename指定下载的文件名(下载时会在客户端显示该名字)
        headers.add("Content-Disposition", "attachment;filename=school.jpg");
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;

        //创建ResponseEntity对象,bytes表示响应体(即图片内容),headers表示响应头,statusCode表示响应状态码
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);

        //关闭输入流
        is.close();
        return responseEntity;
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>index.html页面</h1>

    <a th:href="@{/fileDown}">下载图片</a>
</body>
</html>

二. 文件上传

条件: 

①要有一个form标签,method = "post",enctype必须为"multipart/form-data"

②在form标签中使用input type="file"添加上传文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>index.html页面</h1>

    <form th:href="@{/fileUp}" method="post" enctype="multipart/form-data">
        文件:<input type="file" name="document"/> <br/>
        <input type="submit">
    </form>
</body>
</html>

 ③添加依赖

<!-- 文件上传 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

④在SpringMVC的核心配置文件配置文件上传解析器

<!-- 配置文件上传解析器,将上传的文件封装为MultipartFile -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

实现文件上传:

package com.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class FileUpAndDownController {
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/fileUp")
    public String testFileUp(MultipartFile document, HttpSession session) throws IOException {
        //获取上传的文件的文件名
        String fileName = document.getOriginalFilename();

        //处理文件重名问题(当上传的文件同名,新上传的文件会将原文件覆盖),因此将UUID作为文件名,来解决该问题
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  //获取上传文件的后缀名
        fileName = UUID.randomUUID().toString() + suffixName;  //将UUID和后缀名拼接后的结果作为文件名

        //获取服务器中document目录的路径(将上传的文件放在服务器的document目录下)
        ServletContext servletContext = session.getServletContext();
        String documentPath = servletContext.getRealPath("document");

        //第一次上传时,上述服务器中不存在document目录,需要创建
        File file = new File(documentPath);
        //判断documentPath所对应的路径是否存在
        if(!file.exists()){
            file.mkdir();  //如果不存在,则创建目录
        }

        String finalPath = documentPath + File.separator + fileName;  //File.separator表示路径的分隔符

        //上传
        document.transferTo(new File(finalPath));

        return "index";
    }
}

 上述方法会将上传的目录存放在服务器target目录下的document目录中(如果没有document目录,则创建该目录)

下面的方法是自定义一个存储目录,将上传的文件存放在该目录下。

package com.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class FileUpAndDownController {
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/fileUp")
    public String testFileUp(MultipartFile document, HttpSession session) throws IOException {
        //获取上传的文件的文件名
        String fileName = document.getOriginalFilename();

        //处理文件重名问题(当上传的文件同名,新上传的文件会将原文件覆盖),因此将UUID作为文件名,来解决该问题
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  //获取上传文件的后缀名
        fileName = UUID.randomUUID().toString() + suffixName;  //将UUID和后缀名拼接后的结果作为文件名

        //设置上传的文件存放的目录
        String finalPath = "d:\\" + fileName;

        //上传
        document.transferTo(new File(finalPath));

        return "index";
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值