从零开始 Spring Boot 14:文件上传
文件上传是Web应用相当常见的功能,本篇文章将展示如何在Spring Boot的项目中添加此功能。
假设我们需要在编辑图书时为图书上传一个封面。
依赖
先添加需要的依赖:
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.codec</artifactId>
<version>1.8</version>
</dependency>
配置
再添加需要的配置:
#默认应用运行加载的配置文件
spring.profiles.active=dev
#文件上传目录
books.file.upload.path=D:/workspace/learn_spring_boot/ch14/upload/
#应用使用的域名
books.web.host=localhost
#应用监听端口
server.port=8080
这里项目自定义配置都使用books.xxx
方式命名,当然为避免重复更好的方式是用自己的域名命名。
工具类
为了更方便使用配置项,这里引入一个工具类:
@Data
@Component
public class SysProperties {
@Value("${server.port}")
private String port;
@Value("${books.web.host}")
private String host;
@Value("${books.file.upload.path}")
private String uploadPath;
@Value("${spring.profiles.active}")
private String evn;
}
@Value
注解的用途是将配置中的指定配置项的值绑定到其所在的属性上。举例说明,这里的port
因为@Value
注解的关系,其值就是配置项server.port
的值,也就是8080
。
@Value
中value
属性定义的语法也很简单,类似PHP或Bash中在字符串中使用变量的语法:${xxx}
。
为了给上传功能增加限制,只允许上传照片,这里引入一个文件相关的工具类:
@Component
public class MyFileUtil {
private MimetypesFileTypeMap mtftp;
public MyFileUtil() {
mtftp = new MimetypesFileTypeMap();
/* 不添加下面的类型会造成误判 详见:http://stackoverflow.com/questions/4855627/java-mimetypesfiletypemap-always-returning-application-octet-stream-on-android-e*/
mtftp.addMimeTypes("image png tif jpg jpeg bmp");
}
public boolean isImage(File file) {
//检查后缀名是否是图片
String mimetype = mtftp.getContentType(file);
String type = mimetype.split("/")[0];
if (!type.equals("image")) {
return false;
}
//检查文件内容是否为图片(能否正常获取到高和宽)
try {
BufferedImage bufferedImage = ImageIO.read(file);
if (bufferedImage == null) {
return false;
}
bufferedImage.getHeight();
bufferedImage.getWidth();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 获取文件后缀名
*
* @param fileName
* @return
*/
public String getFileSuffix(String fileName) {
if (fileName == null || fileName