从零开始 Spring Boot 14:文件上传

从零开始 Spring Boot 14:文件上传

spring boot

图源:简书 (jianshu.com)

文件上传是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

@Valuevalue属性定义的语法也很简单,类似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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值