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
package com.yanzuoguang.cloud.file;
import com.yanzuoguang.util.vo.CloudConfig;
import com.yanzuoguang.util.helper.FileHelper;
import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.vo.file.YzgFileBaseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
/**
* 颜佐光上传文件服务文件配置对象
*
* @author 颜佐光
*/
@Component
public class YzgFileConfig {
@Autowired
private CloudConfig cloudConfig;
/**
* 初始化视频
*
* @param serverFile
* @return
*/
public YzgFileBaseVo init(String serverFile) {
YzgFileBaseVo item = new YzgFileBaseVo();
if (!StringHelper.isEmpty(serverFile)) {
init(item, serverFile);
}
return item;
}
/**
* 初始化文件对象
*
* @param item 文件对象
* @param serverFile 默认路径
*/
public void init(YzgFileBaseVo item, String serverFile) {
String fromUrl = getServerPath(serverFile);
// 服务器相对路径
item.setServer(fromUrl);
// 对外显示全路径
item.setDisplay(getUrl(this.cloudConfig.getDisplayUrl(), fromUrl));
// 文件全路径
String serverFullPath = getUrl(this.cloudConfig.getServerUrl(), fromUrl);
// 获取文件大小
File file = new File(serverFullPath);
if (file.exists()) {
item.setSize(file.length());
// 获取mime
item.setMime(FileHelper.getMimeType(serverFullPath));
item.setType(FileHelper.getMediaTypeByMime(item.getMime()));
}
}
/**
* 获取相对路径
*
* @param fromUrl 来源文件
* @return
*/
public String getServerPath(String fromUrl) {
String serverUrl = this.cloudConfig.getServerUrl();
String displayUrl = this.cloudConfig.getDisplayUrl();
// 处理serverFile为简写
if (fromUrl.startsWith(serverUrl)) {
fromUrl = fromUrl.substring(serverUrl.length());
}
if (fromUrl.startsWith(displayUrl)) {
fromUrl = fromUrl.substring(displayUrl.length());
}
return fromUrl;
}
/**
* 获取服务器完全地址
*
* @param fromUrl
* @return
*/
public String getServerFullPath(String fromUrl) {
fromUrl = getServerPath(fromUrl);
return getUrl(this.cloudConfig.getServerUrl(), fromUrl);
}
/**
* 获取服务器完全地址
*
* @param fromUrl
* @return
*/
public String getDisplayPath(String fromUrl) {
fromUrl = getServerPath(fromUrl);
return getUrl(this.cloudConfig.getDisplayUrl(), fromUrl);
}
private String getUrl(String folder, String fromUrl) {
return String.format("%s/%s",
StringHelper.trimEnd(folder, "/"),
StringHelper.trimStart(fromUrl, "/"));
}
}