首页 > 其他分享 >使用SpringBoot实现文件上传和下载

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

时间:2023-12-13 10:02:31浏览次数:29  
标签:文件 SpringBoot boot upload file 上传 下载

上传文件: 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>
这样,我们就实现了文件上传和下载的功能。

参考文章:http://blog.ncmem.com/wordpress/2023/12/05/使用springboot实现文件上传和下载/


 

标签:文件,SpringBoot,boot,upload,file,上传,下载
From: https://blog.51cto.com/u_14023400/8798247

相关文章

  • springboot实现文件的上传下载
    SpringBoot提供了简单易用的方式来处理文件上传和下载功能。下面是一个简单的示例:创建一个文件上传的控制器@RestControllerpublicclassFileUploadController{privatestaticfinalLoggerlogger=LoggerFactory.getLogger(FileUploadController.class);@PostMappi......
  • Spring Boot中的文件上传和下载实现
    文件上传文件上传是Web应用程序中常见的功能之一,SpringBoot提供了MultipartFile接口来处理文件上传。以下是实现文件上传的步骤:添加依赖在pom.xml文件中添加以下依赖:<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</arti......
  • Spring Boot实现文件上传和下载
    实现SpringBoot文件上传和下载的步骤:1.文件上传在pom.xml文件中添加依赖:spring-boot-starter-web和spring-boot-starter-thymeleaf。创建一个上传前端的页面,包括一个表单来选择文件和一个提交按钮。在Controller中添加一个POST方法,该方法接受MultipartFile参数,将文件保存在服务器......
  • Docker部署Transmission | Linux 下的一款 BitTorrent 下载软件
    在【镜像管理】>【镜像仓库】输入关键词transmission进行搜索。搜索结果中,找到要搭建的容器镜像linuxserver/transmission,点击下载或双击镜像即可下载。版本默认选择latest,等待镜像拉取完成即可。​​​​​​创建容器在【镜像管理】>【本地镜像】您可以看到刚刚已下载......
  • 「PPT 下载」Google DevFest Keynote | 复杂的海外网络环境下,如何提升连接质量
    12月10日,“GoogleDevFest2023上海站”大会如期在上海市东方万国宴会中心举办。延续过往的技术交流碰撞、前沿技术学习基调传统,本届大会聚焦行业前瞻、AI洞见、出海加速等议题,吸引数千开发者齐聚一堂、热烈交流。关注【融云全球互联网通信云】了解更多融云IM通讯技术专家吴......
  • 【SpringBootWeb入门-11】MySQL-概述-安装配置
    1、入门前言之前的文章我们讲解了javaweb的springboot框架的入门学习,javaweb开发-数据库也是我们需要学习的核心之一,接下来我们进入MySQL的学习,本篇内容主要讲解MySQL的安装以及配置。2、MySQL下载MySQL官方给我们提供了两种不同的版本:商业版本和社区版本,具体区别如下图:我们......
  • 使用git工具将本地文件上传到github仓库
    使用git工具将本地文件上传到github仓库一、基本步骤第一步:我们需要先创建一个本地的版本库(其实也就是一个文件夹)。第二步:在命令行中输入gitinit把这个文件夹变成Git可管理的仓库然后通过gitadd.("."表示当前文件夹下所有内容都提交,也可以通过gitaddFileName/FolderName......
  • SpringBoot MongoTemplate 实现分页
    一、MongoTemplate实现分页springboot集成Mongodb好像没有现成的分页工具,只能自己先查总数再查数据,需要进行两次查询。例如:@Testpublicvoidtest_119()throwsException{Queryquery=newQuery();longtotal=mongoTemplate.count(query,Dog.class);query.w......
  • java文件的上传与下载
    1、文件上传下载1.1文件上传什么是文件上传?要将客户端(浏览器)大数据存储到服务器端,不将数据直接存储到数据库中,而是要将数据存储到服务器所在的磁盘上,这就要使用文件上传。为什么使用文件上传?通过文件上传,可以将浏览器端的大数据直接保存到服务器端。不将数据保存到数据库中......
  • select for update在springboot里实现分布式锁
    //mapper,注意,这里的参数最好就是主键或者唯一键,否则产生的是表锁@Select("<script>select*fromfoowhereid=#{id}forupdate</script>")FooselectForUpdateById(@Param("id")Longid);//service,必须加事物,否则selectForUpdateById无法实现分布式锁的作用@Transac......