springboot 文件上传下载

1. 新建一个 springboot maven 项目并引入依赖

1. pom.xml

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<!--获取文件扩展名-->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.4</version>
		</dependency>
	</dependencies>

2. 简单的 html 上传下载页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>upload and download</title>
</head>
<body>
<h1>文件上传</h1>
<form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
    <input type="file" name="t1"/>
    <br>
    <input type="submit" value="upload"/>

    <a th:href="@{/product/list}">sss</a>
</form>
<hr>
<h1>文件下载</h1>
<a th:href="@{/file/download(filename='test-mail.rtf')}">test-mail.rtf</a>
<br>
<a th:href="@{/file/download(filename='test-download.txt')}">test-download.txt</a>

</body>
</html>

3. Controller

package com.example.springbootfileuploaddownload.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("file")
public class FileController {

   @GetMapping("init")
   public String init() {
      return "files";
   }

   /**
    * 文件上传
    *
    * @param multipartFile
    * @return
    * @throws IOException
    */
   @PostMapping("upload")
   public String upload(@RequestParam("t1") MultipartFile multipartFile) throws IOException {
      log.info("file name:" + multipartFile.getOriginalFilename());
      log.info("file type:" + multipartFile.getContentType());
      log.info("file size:" + multipartFile.getSize());

//    设置文件路径
      Path realPath = Paths.get(ResourceUtils.getURL("classpath:").getPath() + "static/files");
      if (!Files.exists(realPath)) {
         Files.createDirectories(realPath);
      }
      log.info(Files.exists(realPath) + "");
      log.info("realpath:" + realPath);

//    设置新的文件名
      String newFileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + UUID.randomUUID().toString();
//    获得文件的扩展名
      String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
//    获得新的文件名
      String newFileName = newFileNamePrefix + "." + extension;
      multipartFile.transferTo(Paths.get(realPath.toString(), newFileName));

      return "redirect:init";
   }

  /**
	 * 文件下载
	 * @param filename
	 * @param response
	 * @throws IOException
	 */
   @GetMapping("download")
   public void download(String filename, HttpServletResponse response) throws IOException {
      log.info("filename:" + filename);
//    设置响应头
      response.setHeader("content-disposition", "attachment;fileName=" + filename);

//    根据文件名查找文件
      Path realPath = Paths.get(ResourceUtils.getURL("classpath:").getPath() + "static/files", filename);
      log.info(realPath + "");
//    获得文件输出流
      OutputStream out = response.getOutputStream();
//        将文件拷贝到输出流
      Files.copy(realPath, out);

   }
}

附:

设置上传文件的大小

springboot 默认最大请求为 10M ,最大上传文件为 1M。

可以在 application.properties 中修改默认大小。

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值