基于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接口返回的地址即可访问对应的文件