用Java+阿里云oss搭建图床 后台

本文最后更新于:2022年12月19日 晚上


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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/**
* @author neo.zzj
*/
@Service
public class ImgService {
/**
* Allow upload type (image)
*/
private static final List<String> ALLOW_TYPE = Arrays.asList("image/jpeg", "image/png", "image/bmp");
/**
* oss information
*/
private static String endpoint;
private static String accessKeyId;
private static String accessKeySecret;
private static String bucketName;
private static String key;
static {
Properties props = new Properties();
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("oss.properties");
try {
props.load(is);
endpoint = props.getProperty("endpoint");
accessKeyId = props.getProperty("accessKeyId");
accessKeySecret = props.getProperty("accessKeySecret");
bucketName = props.getProperty("bucketName");
key = props.getProperty("key");
} catch (
IOException e) {
e.printStackTrace();
}
}
/**
* Upload img to aliyun oss
* @param file Image
* @return Img url
*/
public String uploadImg(MultipartFile file) {
// Check file
checkFile(file);
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
InputStream inputStream = null;
try {
String fileName = file.getOriginalFilename();
String name = fileName.substring(0, fileName.lastIndexOf("."));
String prefix = fileName.substring(fileName.lastIndexOf("."));
// Check img is exist and rename
boolean found;
int i = 2;
while (true) {
found = ossClient.doesObjectExist(bucketName, fileName);
if (found) {
fileName = name + "(" + i + ")" + prefix;
i += 1;
} else {
break;
}
}
// Transfer type to file and upload
final File tempFile = File.createTempFile(UUID.randomUUID().toString().replace("-",""), prefix);
file.transferTo(tempFile);
inputStream = new FileInputStream(tempFile);
ossClient.putObject(bucketName, fileName, inputStream);
// Return img url
return "https://img.neoniou.com/" + fileName;
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message: " + oe.getErrorMessage());
System.out.println("Error Code: " + oe.getErrorCode());
System.out.println("Request ID: " + oe.getRequestId());
System.out.println("Host ID: " + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ce.getMessage());
} catch (Throwable e) {
e.printStackTrace();
} finally {
try {
assert inputStream != null;
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
ossClient.shutdown();
}
return null;
}
/**
* Check file type and content
* @param file MultipartFile file
*/
public void checkFile(MultipartFile file) {
try {
// Check file type
String contentType = file.getContentType();
if (!ALLOW_TYPE.contains(contentType)) {
throw new NeoException(ExceptionEnum.INVALID_FILE_TYPE);
}
// Check file content
BufferedImage image = ImageIO.read(file.getInputStream());
if (image == null) {
throw new NeoException(ExceptionEnum.INVALID_FILE_TYPE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Delete temp file
* @param files files
*/
public void deleteTempFile(File... files) {
for (File file : files) {
if (file.exists()) {
file.delete();
}
}
}
}