文件上传的功能实现是我们做Web应用时候最为常见的应用场景,比如:实现头像的上传,Excel文件数据的导入等功能,都需要我们先实现文件的上传,然后再做图片的裁剪,excel数据的解析入库等后续操作。
今天通过这篇文章,我们就来一起学习一下如何在Spring Boot中实现文件的上传,这篇文章主要使用图片上传进行讲解。
主要逻辑为:页面通过form表单上传图片,上传成功之后,在结果页面进行显示、下载与在线预览 等。
具体核心代码,如下
1. pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.neuedu</groupId>
<artifactId>springboot_1213_01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_laoma</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2. resources/templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/uploadfile" method="post" enctype="multipart/form-data">
<label>文件名:</label><input type="file" name="myfile"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
3. resources/templates/show.html
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img th:src="${httpPath}" style="width: 50px;height: 50px"/><br/>
<a th:href="@{/download(name=${newName},openStyle='inline')}">在线预览</a>
<a th:href="@{/download(name=${newName},openStyle='attachment')}">下载</a>
</body>
</html>
4. FileController 代码
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.UUID;
@Controller
public class FileController {
@RequestMapping("/")
private String index(){
return "index";
}
@RequestMapping("/uploadfile")
private String uploadfile(MultipartFile myfile,
HttpServletRequest request,
Model model)throws Exception{
//1. 查看上传文件的信息
//1.1 查看文件的类型
System.out.println("文件的类型:"+myfile.getContentType());
//1.2 文件的名称
System.out.println("文件的名称:"+myfile.getName());
//1.3 文件原名称
System.out.println("文件原名称:"+myfile.getOriginalFilename());
//1.4 文件的大小
System.out.println("文件大小:"+myfile.getSize()+"byte or "+myfile.getSize()/1024 +" KB");
// 综合考虑:两个位置都上传文件
//2. 指定文件上传的目录(target/classes/xxx)
//2.1 /D:/softtools/workspace/workspace_idea/springboot_laoma/target/classes/static/upload/
//2.2 文件存储到此位置,可以提供页面的访问(当时target中的内容不会打包上传到服务器上)
String path_target = ClassUtils.getDefaultClassLoader().getResource("static").getPath()+"/upload/";
//2. 指定文件上传的目录(当前项目的src/main/resources/static/upload 下)
//2.1 文件存储到此位置,可以保存上传的图片,并打包上传到服务器上(在项目中执行 install 就可以生成target中的所有内容)
String path = System.getProperty("user.dir")+"/src/main/resources/static/upload";
//3. 判断此目录是否存在
File fileDir_target = new File(path_target);
if(!fileDir_target.exists()){
fileDir_target.mkdirs();
}
File fileDir = new File(path);
if(!fileDir.exists()){
fileDir.mkdirs();
}
//4. 生成新的名字
String oldName = myfile.getOriginalFilename();
String newName = UUID.randomUUID().toString().replaceAll("-","")+oldName.substring(oldName.lastIndexOf("."),oldName.length());
//5. 指定生成的文件
File file_target = new File(fileDir_target.getAbsolutePath()+File.separator+newName);
File file = new File(fileDir.getAbsolutePath()+File.separator+newName);
//6. 文件的生成
myfile.transferTo(file);
FileCopyUtils.copy(file,file_target);
//7. 生成http的访问路径
String httpPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/"
+ request.getContextPath()+"upload/"+newName;
System.out.println("path:"+path);
System.out.println("path_target:"+path_target);
System.out.println("httpPath:"+httpPath);
//8. 将http的路径返回到页面上
model.addAttribute("httpPath",httpPath);
model.addAttribute("newName",newName);
return "show";
}
@RequestMapping("/download")
private void download(String name, String openStyle, HttpServletResponse response){
try{
//1. 获取下载的路径:当前项目的 src/main/resources/static/upload/
String path = System.getProperty("user.dir")+"/src/main/resources/static/upload";
//2. 图片的加载(将图片转换为输入流)
FileInputStream fis = new FileInputStream(new File(path,name));
//3. 设置在线预览 或 下载
response.setHeader("content-disposition",openStyle+";fileName="+ URLEncoder.encode(name,"UTF-8"));
//4. 获取输出流
ServletOutputStream sos = response.getOutputStream();
//5. 使用文件工具进行文件的拷贝
IOUtils.copy(fis,sos);
//6. 流的关闭
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(sos);
}catch (Exception ex){
ex.printStackTrace();
}
}
}
5. 备注:需要在 resources/static/ 目录下任意创建一个文件,例如:a 文件。否则在程序中读取static文件的时候出错。
到此,整个案例整理完毕!