1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.tanpu.community.manager;
import com.tanpu.common.constant.ErrorCodeConstant;
import com.tanpu.common.exception.BizException;
import com.tanpu.community.api.beans.resp.FileUploadResp;
import com.tanpu.community.api.enums.OssDirEnum;
import com.tanpu.community.dao.entity.community.FileRecordEntity;
import com.tanpu.community.service.OSSFileService;
import com.tanpu.community.util.ConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
public class FileManager {
@Autowired
private OSSFileService ossFileService;
public FileUploadResp uploadFile(MultipartFile file, OssDirEnum dirEnum, String userId) {
if (file == null) {
throw new BizException(ErrorCodeConstant.FILE_UPLOAD_FAIL);
}
byte[] data = null;
try {
data = file.getBytes();
} catch (IOException e) {
throw new BizException(ErrorCodeConstant.FILE_UPLOAD_FAIL);
}
String originalName = file.getOriginalFilename();
if (data.length == 0 || StringUtils.isEmpty(originalName)) {
throw new BizException("上传文件为空");
}
String dirPrefix = "";
if (dirEnum != null) {
dirPrefix = dirPrefix + dirEnum.dir;
}
if (StringUtils.isNotBlank(userId)) {
dirPrefix = dirPrefix + userId + "/";
}
FileRecordEntity fileRecordEntity = ossFileService.uploadFile(data, originalName, dirPrefix);
return ConvertUtil.fileRecordEntity2Resp(fileRecordEntity);
}
public Map<String, String> getFileUrlByIds(List<String> fileIds) {
return ossFileService.queryByIds(fileIds).stream()
.collect(Collectors.toMap(FileRecordEntity::getFileId, FileRecordEntity::getUrl));
}
}