基于springboot搭建属于自己的文件存储系统

基于springboot搭建属于自己的文件存储系统

配置信息
oss:
  config:
    path: /Users/zero/Desktop/pic/ #需要替换存储地址
    prefix: https://xxx.xxx.com  #需要替换访问域名(项目地址本地可以使用内网穿透或者localhost:端口)
}
配置类
@ConfigurationProperties(prefix = "oss.config")
@Data
@Component
@RefreshScope
public class OssConfigSetting {

    @ApiModelProperty("文件路径")
    private String path;

    @ApiModelProperty("文件地址前缀")
    private String prefix;
}
工具类
 @Autowired
    private OssConfigSetting ossConfigSetting;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd/");

    //上传文件
    public String uploadFile(MultipartFile uploadFile){
        String format = sdf.format(new Date());
        File folder = new File(ossConfigSetting.getPath() + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        // 对上传的文件重命名,避免文件重名
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        String filePath=null;
        try {
            // 文件保存
            uploadFile.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径
            filePath = ossConfigSetting.getPrefix() +"/pic/"+ format + newName;
        } catch (IOException e) {
            throw new RuntimeException("上传失败");
        }
        return filePath;
    }
mvc配置文件访问
@Configuration
public class FileConfig implements WebMvcConfigurer {

    @Value("${oss.config.path}")
    private String path;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pic/**")
                .addResourceLocations("file:"+path);
    }

}

这些代码嵌入项目即可完成简单的文件上传,通过springboot接口返回的地址即可访问对应的文件

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值