文件上传功能-本地存储、阿里OSS、七牛云
生活随笔
收集整理的這篇文章主要介紹了
文件上传功能-本地存储、阿里OSS、七牛云
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
工廠類
@Autowired private FileServiceFactory fileServiceFactory; @Configuration public class FileServiceFactory {private Map<FileSource, FileService> map = new HashMap<>();@Autowiredprivate FileService localFileServiceImpl;@Autowiredprivate FileService aliyunFileServiceImpl;@PostConstructpublic void init() {map.put(FileSource.LOCAL, localFileServiceImpl);map.put(FileSource.ALIYUN, aliyunFileServiceImpl);}public FileService getFileService(String fileSource) {if (StringUtils.isBlank(fileSource)) {return localFileServiceImpl;}return map.get(FileSource.valueOf(fileSource));}文件上傳抽象類
@Slf4j public abstract class AbstractFileService implements FileService {protected abstract FileDao getFileDao();@Overridepublic FileInfo upload(MultipartFile file) throws Exception {FileInfo fileInfo = FileUtil.getFileInfo(file);FileInfo oldFileInfo = getFileDao().getById(fileInfo.getId());if (oldFileInfo != null) {return oldFileInfo;}if (!fileInfo.getName().contains(".")) {throw new IllegalArgumentException("缺少后綴名");}uploadFile(file, fileInfo);fileInfo.setSource(fileSource().name());// 設置文件來源getFileDao().save(fileInfo);// 將文件信息保存到數據庫log.info("上傳文件:{}", fileInfo);return fileInfo;}/*** 文件來源* * @return*/protected abstract FileSource fileSource();/*** 上傳文件* * @param file* @param fileInfo*/protected abstract void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception;@Overridepublic void delete(FileInfo fileInfo) {deleteFile(fileInfo);getFileDao().delete(fileInfo.getId());log.info("刪除文件:{}", fileInfo);}/*** 刪除文件資源* * @param fileInfo* @return*/protected abstract boolean deleteFile(FileInfo fileInfo); }本地實現類
/*** 本地存儲文件<br>* 該實現文件服務只能部署一臺<br>* 如多臺機器間能共享到一個目錄,即可部署多臺**/ @Service("localFileServiceImpl") public class LocalFileServiceImpl extends AbstractFileService {@Autowiredprivate FileDao fileDao;@Overrideprotected FileDao getFileDao() {return fileDao;}@Value("${file.local.urlPrefix}")private String urlPrefix;/*** 上傳文件存儲在本地的根路徑*/@Value("${file.local.path}")private String localFilePath;@Overrideprotected FileSource fileSource() {return FileSource.LOCAL;}@Overrideprotected void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception {int index = fileInfo.getName().lastIndexOf(".");// 文件擴展名String fileSuffix = fileInfo.getName().substring(index);String suffix = "/" + LocalDate.now().toString().replace("-", "/") + "/" + fileInfo.getId() + fileSuffix;String path = localFilePath + suffix;String url = urlPrefix + suffix;fileInfo.setPath(path);fileInfo.setUrl(url);FileUtil.saveFile(file, path);}@Overrideprotected boolean deleteFile(FileInfo fileInfo) {return FileUtil.deleteFile(fileInfo.getPath());} }阿里云實現類,需要導入oss的pom依賴
/*** 阿里云存儲文件**/ @Service("aliyunFileServiceImpl") public class AliyunFileServiceImpl extends AbstractFileService {@Autowiredprivate FileDao fileDao;@Overrideprotected FileDao getFileDao() {return fileDao;}@Overrideprotected FileSource fileSource() {return FileSource.ALIYUN;}@Autowiredprivate OSSClient ossClient;@Value("${file.aliyun.bucketName}")private String bucketName;@Value("${file.aliyun.domain}")private String domain;@Overrideprotected void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception {ossClient.putObject(bucketName, fileInfo.getName(), file.getInputStream());fileInfo.setUrl(domain + "/" + fileInfo.getName());}@Overrideprotected boolean deleteFile(FileInfo fileInfo) {ossClient.deleteObject(bucketName, fileInfo.getName());return true;}}文件上傳工具類
public class FileUtil {public static FileInfo getFileInfo(MultipartFile file) throws Exception {String md5 = fileMd5(file.getInputStream());FileInfo fileInfo = new FileInfo();fileInfo.setId(md5);// 將文件的md5設置為文件表的idfileInfo.setName(file.getOriginalFilename());fileInfo.setContentType(file.getContentType());fileInfo.setIsImg(fileInfo.getContentType().startsWith("image/"));fileInfo.setSize(file.getSize());fileInfo.setCreateTime(new Date());return fileInfo;}/*** 文件的md5* * @param inputStream* @return*/public static String fileMd5(InputStream inputStream) {try {return DigestUtils.md5Hex(inputStream);} catch (IOException e) {e.printStackTrace();}return null;}public static String saveFile(MultipartFile file, String path) {try {File targetFile = new File(path);if (targetFile.exists()) {return path;}if (!targetFile.getParentFile().exists()) {targetFile.getParentFile().mkdirs();}file.transferTo(targetFile);return path;} catch (Exception e) {e.printStackTrace();}return null;}public static boolean deleteFile(String pathname) {File file = new File(pathname);if (file.exists()) {boolean flag = file.delete();if (flag) {File[] files = file.getParentFile().listFiles();if (files == null || files.length == 0) {file.getParentFile().delete();}}return flag;}return false;}public static String getPath() {return "/" + LocalDate.now().toString().replace("-", "/") + "/";}/*** 將文本寫入文件** @param value* @param path*/public static void saveTextFile(String value, String path) {FileWriter writer = null;try {File file = new File(path);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}writer = new FileWriter(file);writer.write(value);writer.flush();} catch (IOException e) {e.printStackTrace();} finally {try {if (writer != null) {writer.close();}} catch (IOException e) {e.printStackTrace();}}}public static String getText(String path) {File file = new File(path);if (!file.exists()) {return null;}try {return getText(new FileInputStream(file));} catch (FileNotFoundException e) {e.printStackTrace();}return null;}public static String getText(InputStream inputStream) {InputStreamReader isr = null;BufferedReader bufferedReader = null;try {isr = new InputStreamReader(inputStream, "utf-8");bufferedReader = new BufferedReader(isr);StringBuilder builder = new StringBuilder();String string;while ((string = bufferedReader.readLine()) != null) {string = string + "\n";builder.append(string);}return builder.toString();} catch (IOException e) {e.printStackTrace();} finally {if (bufferedReader != null) {try {bufferedReader.close();} catch (IOException e) {e.printStackTrace();}}if (isr != null) {try {isr.close();} catch (IOException e) {e.printStackTrace();}}}return null;}}?
總結
以上是生活随笔為你收集整理的文件上传功能-本地存储、阿里OSS、七牛云的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 项目中使用EasyPOI完成监控设备历史
- 下一篇: 本地上传流程梳理