Spring Boot文件上传下载

SpringBoot需要引用Apache Commons FileUpload组件依赖,在pom.xml配置

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

文件上传参数配置application.properties:

单文件最大50MB

spring.servlet.multipart.max-file-size=50MB

整个请求大小最大500MB,换言之就是上传多个文件总大小不超过500MB

spring.servlet.multipart.max-request-size=500MB

文件上传:

html:

<h1>表单提交</h1>
<form action="upload" enctype="multipart/form-data" method="post">
    文件描述:<input type="text"  name="context" ><br>
    文件:<input type="file" name="file"><br>
    <input type="submit" value="上传">
</form>

Controller:

 @RequestMapping("/upload")
    public String upload(HttpServletRequest request, @RequestParam("context") String context, @RequestParam("file")MultipartFile file){
        System.out.println("文件描述:"+context);
        if(!file.isEmpty()){
            String path="D:/Test";
            String filename=file.getOriginalFilename();
            File filepath=new File(path+File.separator+filename);
            if(!filepath.getParentFile().exists())filepath.getParentFile().mkdirs();
            System.out.println(filepath.getAbsolutePath());
            try {
                file.transferTo(filepath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

/******          以上代码已将上传的文件放入到path中 ,这里返回展示已上传文件的页面         ******/
        return "forward:/showDownLoad";
    }

设置下载页面:

Controller:

//将文件列表显示出来    
    @RequestMapping("/showDownLoad")
    public String showDownLoad(HttpServletRequest request, Model model){
        String path="D:/Test";
        File filedir=new File(path);
        File[] fileList=filedir.listFiles();
        model.addAttribute("filesList",fileList);
        return "index";
    }

//以流的方式将文件输出
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request,@RequestParam("filename") String filename,@RequestHeader("User-Agent") String userAgent){
        String path="D:/Test";
        File downfile=new File(path+File.separator+filename);
        ResponseEntity.BodyBuilder builder=ResponseEntity.ok();
        builder.contentLength(downfile.length());
        builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            filename= URLEncoder.encode(filename,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(userAgent.indexOf("MSIE")>0){
            builder.header("Content-Disposition","attachment;filename="+filename);
        }else{
            builder.header("Content-Disposition","attachment;filename*=UTF-8''"+filename);
        }

        try {
            return builder.body(FileUtils.readFileToByteArray(downfile));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

html:这里用了Thymeleaf模板

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<table>
    <tr th:each="file,stat:${filesList}">
        <td><span th:text="${stat.count}"></span></td>
        <td><a th:href="@{download(filename=${file.name})}" ><span th:text="${file.name}"></span></a></td>
    </tr>
</table>
</body>
</html>

这里的

<td><a th:href="@{download(filename=${file.name})}" ><span th:text="${file.name}">

会被加载成,例:

<td><a href="download?filename=2017.jpg"><span>2017.jpg</span></a></td>

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是 Spring Boot 实现文件上传下载的代码示例: 文件上传: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try { // 保存文件到本地 Path filePath = Paths.get("uploads", file.getOriginalFilename()); Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING); return "上传成功"; } catch (Exception e) { return "上传失败:" + e.getMessage(); } } ``` 文件下载: ```java @GetMapping("/download") public ResponseEntity<Resource> downloadFile(@RequestParam("fileName") String fileName) { try { // 读取文件 Path filePath = Paths.get("uploads", fileName); Resource resource = new UrlResource(filePath.toUri()); // 构建响应实体 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName); return ResponseEntity.ok() .headers(headers) .contentLength(resource.contentLength()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } ``` 其中,`@PostMapping("/upload")` 和 `@GetMapping("/download")` 是 Spring MVC 的注解,分别用于处理文件上传和文件下载的请求。在文件上传方法中,使用 `@RequestParam("file")` 注解来获取上传的文件。在文件下载方法中,使用 `@RequestParam("fileName")` 注解来获取需要下载的文件名。 在上传文件时,将文件保存到指定的本地路径中,这里使用了 `Files.copy()` 方法。在下载文件时,先将文件读取为 `Resource` 类型,然后使用 Spring 的 `ResponseEntity` 构建一个响应实体,设置响应头和响应体,最后返回给客户端即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值