package com.yanzuoguang.cloud.file; import com.yanzuoguang.cloud.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, "/")); } }