springboot 简单的文件上传与下载

springboot 文件上传下载

  • 1. 新建一个 springboot maven 项目并引入依赖
    • 1. pom.xml
    • 2. 简单的 html 上传下载页面
    • 3. Controller
  • 附:
    • 设置上传文件的大小

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

1. pom.xml

	<dependencies>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-devtoolsartifactId>
			<scope>runtimescope>
			<optional>trueoptional>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintagegroupId>
					<artifactId>junit-vintage-engineartifactId>
				exclusion>
			exclusions>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-thymeleafartifactId>
		dependency>
		<dependency>
			<groupId>org.projectlombokgroupId>
			<artifactId>lombokartifactId>
		dependency>
		
		<dependency>
			<groupId>commons-fileuploadgroupId>
			<artifactId>commons-fileuploadartifactId>
			<version>1.4version>
		dependency>
	dependencies>

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


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>upload and downloadtitle>
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}">sssa>
form>
<hr>
<h1>文件下载h1>
<a th:href="@{/file/download(filename='test-mail.rtf')}">test-mail.rtfa>
<br>
<a th:href="@{/file/download(filename='test-download.txt')}">test-download.txta>

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

你可能感兴趣的:(springboot,upload,spring,boot,spring,download)