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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.tanpu.community.service;
import com.tanpu.common.constant.BizStatus;
import com.tanpu.common.util.AliyunOSSHelper;
import com.tanpu.community.api.enums.OssRelType;
import com.tanpu.community.dao.entity.community.FileRecordEntity;
import com.tanpu.community.dao.mapper.community.FileRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
@Slf4j
@Service
public class OSSFileService {
@Value("${aliyun.oss.endpoint}")
public String endpoint;
@Value("${aliyun.oss.accessId}")
public String accessId;
@Value("${aliyun.oss.accessSK}")
public String accessSK;
@Value("${aliyun.oss.bucketName}")
public String bucketName;
private AliyunOSSHelper ossHelper;
@Resource
private FileRecordMapper fileRecordMapper;
@PostConstruct
public void init() {
ossHelper = AliyunOSSHelper.build(endpoint, accessId, accessSK);
}
@Transactional
public FileRecordEntity uploadFile(byte[] data, String fileName) {
String fileSuffix = fileName.substring(fileName.lastIndexOf('.') + 1);
return uploadFile(data, fileName, fileSuffix, null, OssRelType.None);
}
@Transactional
public FileRecordEntity uploadFile(byte[] data, String fileName, String relId, OssRelType relType) {
String fileSuffix = fileName.substring(fileName.lastIndexOf('.') + 1);
return uploadFile(data, fileName, fileSuffix, relId, relType);
}
@Transactional
public FileRecordEntity uploadFile(byte[] data, String fileName, String fileSuffix,
String relId, OssRelType relType) {
// todo uniqueLong
String key = String.valueOf(System.currentTimeMillis());
String id = String.valueOf(System.currentTimeMillis());
ossHelper.writeFile(bucketName, key, data, fileSuffix);
FileRecordEntity record = new FileRecordEntity();
record.setId(id);
record.setDeleteTag(BizStatus.DeleteTag.tag_init);
record.setLogicKey(key);
record.setOriginalName(fileName);
record.setPresignedUrl(ossHelper.getPreSignedUrl(bucketName, key));
record.setRelType(relType.type);
record.setRelId(relId);
fileRecordMapper.insert(record);
return record;
}
}