
{{wikiTitle}}
上传文件图片
目录:
一、功能概述
本模块提供统一文件上传服务,支持本地存储及主流云存储服务(阿里云OSS、腾讯云COS、七牛云、京东云)。
核心功能包括:
1.文件格式/大小校验
2.多存储服务动态切换
3.文件元数据记录
4.自动清理临时文件
二、接口说明
1. 图片文件上传接口
@ApiOperation(value = "图片上传")
@PostMapping("/image")
public CommonResult<FileResultVo> imageUpload(
@RequestPart MultipartFile multipart,
@RequestParam String model, // 业务模块标识
@RequestParam Integer pid // 分类ID
)
@ApiOperation(value = "文件上传")
@PostMapping("/file")
public CommonResult<FileResultVo> fileUpload(
@RequestPart MultipartFile multipart,
@RequestParam String model,
@RequestParam Integer pid
)
管理端可以配置相关文件后缀和大小限制上传参数
/**
* 上传校验
*
* @param fileName 文件名称
* @param fileSize 文件大小
* @return 后缀名
*/
private String uploadValidate(String fileName, float fileSize, String fileType, String contentType) {
...
// 判断文件的后缀名是否符合规则
if (!extensionList.contains(extName)) {
throw new CrmebException(CommonResultCode.VALIDATE_FAILED, "上载文件类型只能为:" + extStr);}
...
// 文件大小验证
if (fileSize > size) {
throw new CrmebException(CommonResultCode.VALIDATE_FAILED, StrUtil.format("最大允许上传 {} MB文件,当前文件大小为 {} MB", size, fs));}
...
}
三、核心流程
1. 上传校验流程
start
:接收上传请求;
:检查文件是否为空? -> 是: 抛出异常;
:获取文件原始名;
:提取文件后缀名;
if (后缀名不在白名单?) then (是)
:抛出"不支持格式"异常;
stop
endif
:计算文件大小MB;
if (超过配置大小?) then (是)
:抛出"文件过大"异常;
stop
endif
end
2. 存储路径生成规则
{存储根目录}/{文件类型}/{模块}/{年/月/日}/{随机文件名}.{后缀}
示例:
crmebimage/public/product/2023/07/15/abcd1234.jpg
3. 多存储服务调度
// 根据配置选择存储方式
switch(uploadType) {
case 1: // 本地存储
saveToLocal();
break;
case 2: // 七牛云
qiniuClient.upload();
break;
case 3: // 阿里OSS
ossClient.putObject();
break;
case 4: // 腾讯COS
cosClient.upload();
break;
case 5: // 京东云
jdCloud.upload();
break;
}
四、二开策略
1. 新增存储服务商
实现步骤:
新增枚举类型
public enum StorageType {
LOCAL, QINIU, OSS, COS, JDCLOUD, CUSTOM
}
实现存储接口
public interface StorageService {
String upload(File file, String key);
boolean delete(String key);
}
注入Spring容器
@Service("customStorage")
public class CustomStorageImpl implements StorageService {
// 实现具体逻辑
}
2. 自定义存储路径
修改路径生成策略:
// 原路径生成
String webPath = "public/"+model+"/"+datePath;
// 改为动态配置
@Value("${upload.path.rule:defaultRule}")
private String pathRule;
// 使用SPEL解析规则
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(pathRule);
3. 添加文件处理钩子
实现后处理逻辑:
public class FileUploadListener {
@Async
@EventListener
public void handleUploadEvent(FileUploadEvent event) {
// 生成缩略图
thumbnailService.generate(event.getFile());
// 病毒扫描
antivirusService.scan(event.getFile());
}
}




评论({{cateWiki.comment_num}})
{{commentWhere.order ? '评论从旧到新':'评论从新到旧'}}
{{cateWiki.page_view_num}}人看过该文档


评论(0)
{{commentWhere.order ? '评论从旧到新':'评论从新到旧'}}
269人看过该文档




{{item.user ? item.user.nickname : ''}}
(自评)
{{item.content}}
{{item.create_time}}
删除




搜索结果
为您找到{{wikiCount}}条结果
{{item.page_view_num}}
{{item.like ? item.like.like_num : 0}}
{{item.comment ? item.comment.comment_num : 0}}
位置:
{{path.name}}
{{(i+1) == item.catalogue.path_data.length ? '':'/'}}


