[每日一记]2022-08-19

本文讨论了Spring Boot在处理MultipartFile上传时,默认临时目录可能遇到的Linux系统自动清理问题,并介绍了如何通过配置自定义临时文件路径来避免这个问题。示例展示了使用@Configuration类和配置文件设置自定义路径的方法,确保上传文件的安全存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 一、MultipartFile 上传文件临时目录自动清理机制隐患

1、默认存储在/tmp下,  但是linux的/tmp有自动清理的机制,

cat /usr/lib/tmpfiles.d/tmp.conf

#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published by
#  the Free Software Foundation; either version 2.1 of the License, or
#  (at your option) any later version.

# See tmpfiles.d(5) for details

# Clear tmp directories separately, to make them easier to override
v /tmp 1777 root root 10d
v /var/tmp 1777 root root 30d

# Exclude namespace mountpoints created with PrivateTmp=yes
x /tmp/systemd-private-%b-*
X /tmp/systemd-private-%b-*/tmp
x /var/tmp/systemd-private-%b-*
X /var/tmp/systemd-private-%b-*/tmp

 2、改变默认位置

采用配置类:

@Configuration
public class MultipartConfig {

    /**
     * 文件上传临时路径
     */
    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        String location = "自定义临时文件路径";
        File tmpFile = new File(location);
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        factory.setLocation(location);
        return factory.createMultipartConfig();
    }
}

配置文件方式:

#指定multipartFile临时文件存放路径,但是内置的tomcat创建的临时文件夹路径还是不变的
spring.servlet.multipart.location=临时文件路径
#指定springboot启动时内置tomcat创建的临时文件夹的路径
#server.tomcat.basedir=/data/ops/app/cms/cache

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值