使用SpringBoot实现文件上传和下载

上传文件: 1.在 `pom.xml` 文件中添加依赖:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-tomcat</artifactId>
   <scope>provided</scope>
</dependency>
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
</dependency>

2.编写上传页面,例如在 `upload.html` 文件中:

html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <div>
            <label for="file">选择文件: </label>
            <input type="file" id="file" name="file"/>
        </div>
        <div>
            <input type="submit" value="上传"/>
        </div>
    </form>
</body>
</html>

3.编写上传逻辑

@Controller
public class FileController {

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file,
                         RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请选择一个文件上传!");
            return "redirect:/";
        }
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(file.getOriginalFilename());
            Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("message", "上传成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/";
    }

}

下载文件: 1.创建一个接口,用于下载文件。

@Controller
public class FileDownloadController {

    @Autowired
    private ServletContext servletContext;

    /**
     * 下载文件
     */
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam(defaultValue = "") String fileName) throws Exception {
        if (fileName.isEmpty()) {
            returnbuild();
 String filePath Resource resource);
        if (!resource.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        String contentType = servletContext.getMimeType(resource.getFile().getAbsolutePath());
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

}

2.在 `application.properties` 文件中添加如下配置或在配置文件中指定下载文件目录:

properties
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
file.upload-dir=/path/to/upload/files/

3.在 `application.properties` 中开启下载目录访问:

properties
spring.mvc.static-path-pattern=/download/**
spring.resources.static-locations=file:/path/to/upload/files/

4.编写 download.html 页面:

html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件下载</title>
</head>
<body>
    <form action="/download" method="get">
        <label for="filename">文件名: </label>
        <input type="text" id="filename" name="fileName"/>
        <button type="submit">下载</button>
    </form>
</body>
</html>

5.在 `index.html` 页面添加下载链接:

html
<a href="/download">下载文件</a>

这样,我们就实现了文件上传和下载的功能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值