SpringMVC实现文件上传&下载功能

文件上传

说明:
使用maven构建web工程。
使用Thymeleaf技术进行服务器页面渲染。

使用ResponseEntity实现下载文件的功能。

@Controller
public class FileDownloadAndUpload {

    @GetMapping("/file/download")
    public ResponseEntity<byte[]> fileDownload(HttpSession session) {
        //获取servletContext对象
        ServletContext servletContext = session.getServletContext();

        /*
        路径空串:maven工程中获取的是当前web工程target下的war包路径
        D:\spring-workspace\springmvc-pro\springmvc-filedownupload\target\springmvc-filedownupload-1.0-SNAPSHOT
         */
        //String realPath = servletContext.getRealPath("");

        //获取服务器中文件的真实路径
        String path = File.separator + "imgs" + File.separator + "dog.jpg";
        String realPath = servletContext.getRealPath(path);

        ResponseEntity<byte[]> responseEntity = null;
        try (
                //创建字节输入流
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath))
        ) {
            //创建字节数组
            byte[] buff = new byte[bis.available()];
            //将流读入到字节数组中
            bis.read(buff);
            //创建HttpHeaders对象设置响应头信息
            MultiValueMap<String, String> headers = new HttpHeaders();
            //设置要下载方式以及下载文件的名字
            headers.add("Content-Disposition", "attachment;filename=dog.jpg");
            //设置响应状态码
            HttpStatus statusCode = HttpStatus.OK;
            //创建ResponseEntity对象
            responseEntity = new ResponseEntity<>(buff, headers, statusCode);
            return responseEntity;
        }  catch (IOException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("文件下载出现异常");
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <a th:href="@{/file/download}">文件下载</a><br/>
</body>
</html>

文件下载

文件上传要求form表单的请求方式必须为post,并且添加属性enctype="multipart/form-data"
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息。
实现文件下载步骤:
step 1: 添加依赖

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.3</version>
</dependency>

step 2:在springmvc配置文件中添加文件解析器

<!-- 通过文件解析器的解析才能将文件转换为MultipartFile对象,并且id必须为multipartResolver -->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver" />

setp 3:编写文件下载逻辑

@Controller
public class FileDownloadAndUpload {
@PostMapping("/file/upload")
    public String fileUpload(@RequestParam("photo") MultipartFile photo, HttpSession session) {
        //获取servletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取上传文件的文件名
        String filename = photo.getOriginalFilename();
        //文件重命名问题
        if (filename != null) {
            //获取文件后缀
            String suffixFileName = filename.substring(filename.lastIndexOf("."));
            //通过UUID重命名文件名
            filename = UUID.randomUUID().toString() + suffixFileName;
        }
        //获取服务器中文件所在路径
        String realPath = servletContext.getRealPath("imgs");
        File file = new File(realPath);
        //判断文件目录是否存在
        if (!file.exists()) {
            file.mkdir();
        }
        //文件最终上传的路径
        String filePath = realPath + File.separator + filename;
        //实现上传
        try {
            photo.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
}

step 4:编写form表单

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件下载</title>
</head>
<body>
    <form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
        <input type="file" name="photo"><br/>
        <input type="submit" value="点击上传"><br/>
    </form>
</body>
</html>
posted @ 2024-01-31 01:56  Evan1024  阅读(116)  评论(0编辑  收藏  举报