基于SpringBoot的文件上传方式有:
1、直接上传到应用服务器
2、上传到OSS(阿里云、七牛云)
3、前端将图片转成Base64编码上传(仅适用于小容量的图片)
下面的实例就是将文件上传到服务器,将上传路径设定为项目目录,如static目录,并通过UUID生成随机的主文件名,扩展名不变
在SpringBoot模块中实现文件的上传实例(upload模块)
1、新建SpringBoot——upload模块,填写模块名、描述等信息

2、选中 Web 和 Thymeleaf 按钮,点击下一步


3、检查模块的名字、路径等信息

4、模块新建完成后的模块结构

5、配置application.properties,指定上传文件的大小限制等
# 文件上传的配置
#文件上传的最大限制
spring.servlet.multipart.max-file-size = 100MB
6、在 templates 文件夹下新建 upload.html 和 upload_status.html 页面
6.1、upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spring Boot文件上传页面</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
6.2、upload_status.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件上传状态显示</title>
</head>
<body>
<h2>Spring Boot的文件上传状态</h2>
<div th:if="${message}">
<h2 th:text="${message}"></h2>
</div>
</body>
</html>
message报错不影响
7、编写 Controller ,实现 java.nio 实现文件的上传
package com.springboot.upload.controller;
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.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.File;
import java.io.IOException;
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;
/**
* 上传文件控制器
* 直接上传到服务器
* Created by Administrator on 2019/3/25.
*/
@Controller
public class UploadController {
//指定一个临时路径作为上传目录
//private static String UPLOAD_FOLDER = "C:\\Users\\Liuyu\\Desktop\\UPLOAD\\";
//遇到http://localhost:8080,则跳转至upload.html页面
@GetMapping("/")
public String index() {
return "upload";
}
@PostMapping("upload")
public String fileUpload(@RequestParam("file") MultipartFile srcFile, RedirectAttributes redirectAttributes) {
//前端没有选择文件,srcFile为空
if (srcFile.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "请选择一个文件");
return "redirect:upload_status";
}
//选择了文件,开始上传操作
try {
//构建上传目标路径,找到了项目的target的classes目录
File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
if (!destFile.exists()) {
destFile = new File("");
}
//输出目标文件的绝对路径
System.out.println("file path:" + destFile.getAbsolutePath());
//拼接子路径
SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
String times = sf_.format(new Date());
File upload = new File(destFile.getAbsolutePath(), "static/" + times);
//若目标文件夹不存在,则创建
if (!upload.exists()) {
upload.mkdirs();
}
System.out.println("完整的上传路径:" + upload.getAbsolutePath() + "/" + srcFile);
//根据srcFile大小,准备一个字节数组
byte[] bytes = srcFile.getBytes();
//拼接上传路径
//Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件原始名称
String fileName = srcFile.getOriginalFilename();
// 获得文件后缀名称
String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// 生成最新的uuid文件名称
String newFileName = uuid + "." + suffixName;
//通过项目路径,拼接上传路径
Path path = Paths.get(upload.getAbsolutePath() + "/" + newFileName);
//** 开始将源文件写入目标地址
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message", "文件上传成功" + newFileName);
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:upload_status";
}
//匹配upload_status页面
@GetMapping("upload_status")
public String uploadStatusPage() {
return "upload_status";
}
}
8、在UploadApplication 运行项目成功后在浏览器输入:http://localhost:8080



9、也可以将项目打成jar包,输入控制台命令"java -jar XXX"(XXX代表jar包名),运行成功之后在浏览器输入:http://localhost:8080,可以和第8点得到同样的结果
9.1、删除 target 目录,一定要停止运行刚才在Application中的运行(否则运行失败)
9.2、点击右侧Maven目录,找到upload项目的Lifecycle,依次双击 clean 和 install ,出现 "BUILD SUCCESS" 成功


9.3、复制target目录下的 .jar 文件到任意目录

9.4、在复制路径下运行命令:java -jar XXX(XXX代表jar包名),如下图

9.5、在留言器运行:http://localhost:8080,运行成功如下

9.6、在jar的同级目录下会创建 static 文件夹来存放上传的文件

自动根据时间创建文件夹,并将上传文件名字改为uuid格式


如果有不懂得,可以看github上的源码:spring-boot-study下的upload模块
网友评论