2021SC@SDUSC
目录
一、Attachment
Attachment类是io.jpress.model包下的附件类,映射了数据库中的“attachment”表,里面有许多关于附件的方法和属性,可以判断附件的属性,查看附件是否是本地附件等。
它先自定义了附件的后缀,如下:
private static List<String> imageSuffix = Lists.newArrayList(".jpg", ".jpeg", ".png", ".bmp", ".gif", ".webp"); private static List<String> docSuffix = Lists.newArrayList(".doc", ".docx", ".pages", ".dot", ".dotx", ".docm", ".dotm"); private static List<String> xlsSuffix = Lists.newArrayList(".xls", ".xlsx", ".xltx", ".numbers", ".csv"); private static List<String> pptSuffix = Lists.newArrayList(".ppt", ".pptx", ".key", ".ppsx", ".potx"); private static List<String> txtSuffix = Lists.newArrayList(".txt", ".log", ".xml", ".json", ".js", ".css", ".html", ".sql", ".md"); private static List<String> zipSuffix = Lists.newArrayList(".zip", ".tar", ".gz", ".jar", ".war", ".bz2", ".z"); private static List<String> rarSuffix = Lists.newArrayList(".rar"); private static List<String> exeSuffix = Lists.newArrayList(".exe", ".pkg", ".dmg"); private static List<String> pdfSuffix = Lists.newArrayList(".pdf"); private static List<String> audioSuffix = Lists.newArrayList(".mp3", ".au", ".cd", ".wma", ".ogg", ".ape", ".flac", ".aiff"); private static List<String> videoSuffix = Lists.newArrayList(".mp4", ".avi", ".wmv", ".mpeg", ".mov", ".mkv", ".flv", ".rmvb", ".rm", ".3gp", ".ts", ".vob", ".m3u8");
可以看到,JPress是支持这些附件的上传和下载的。然后提供一个suffixIn()函数来判断附件的格式,方法如下:
private boolean suffixIn(List<String> suffixList) { String suffix = StrUtil.obtainDefaultIfBlank(getSuffix(),FileUtil.getSuffix(getPath())); return suffix != null && suffixList.contains(suffix.toLowerCase()); }
可以看到,如果一个附件的suffix后缀中是属于某类型suffixList的一项,那他将会被分类到该属性,使用了list的contains()方法判断。
除了这些,Attachment类还继承了BaseAttachment类,拥有获取主键ID、用户ID、标题、附件描述、路径、后缀、类型、上传时间等方法。
继续往上探讨,BaseAttachment类继承JbootModel类,而JbootModel类是JBoot框架中映射数据库表的类,所以这就是Attachment类对应数据库中attachment表的原因,它的父类的父类是JbootModel类。
二、AttachmentDownloader
AttachmentDownloader是JPress.core包下负责把远程的附件本地化的工具,它主要负责的功能是下载远程附件,下载成功后更新 attachment本身的路径。
private static void doDownload(Attachment attachment) { if (attachment.isLocal()) { return; } String url = attachment.getPath(); if (StrUtil.isBlank(url)) { return; } String path = "/attachment" + URI.create(url).getPath(); File downloadToFile = AttachmentUtils.file(path); JbootHttpRequest request = JbootHttpRequest.create(url); request.setDownloadFile(downloadToFile); JbootHttpResponse response = HttpUtil.handle(request); if (response.isError()) { LogKit.error("download attachment error by url:" + url); return; } attachment.setMimeType(response.getContentType()); attachment.setPath(path); attachment.update(); }
核心代码如上,可以分析一下它的思路。附件有几个不需要下载的情况:该附件是本地的、该附件的下载地址是空的(这可能是个错误的附件)。其他情况下,该文件需要下载,该方法先拼接出下载的URL,再通过JbootHttpRequest工具类下载,如果返回的response是正常的,那么就可以更新该附件在数据库中的类型、本地路径。
以上就是JPress的附件管理模块。