基於tobato的fastdfs與spring boot整合實現檔案上傳和下載
阿新 • • 發佈:2019-01-09
專案結構:
pom.xml檔案新增配置:
<!-- fastdfs --> <dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.26.2</version> </dependency>
application.yml新增配置:
#fastdfs 配置 fdfs: so-timeout: 1500 connect-timeout: 600 thumb-image: width: 150 height: 150 tracker-list: - 10.3.10.173:22122
包含載入時間,連線時間,圖片長寬高等欄位。除了tracker-list:服務地址,其他的都不是必須的,其他具體配置這裡不做詳細解釋。
檔案上傳html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <meta charset="UTF-8" /> <title>Insert title here</title> </head> <body> <h1 th:inlines="text">檔案上傳</h1> <form action="upload" method="post" enctype="multipart/form-data"> <p>選擇檔案: <input type="file" name="fileName"/></p> <p><input type="submit" value="提交"/></p> </form> </body> </html>
在controller中訪問html檔案
/* * 獲取fileUploade.html頁面 */ @RequestMapping("file") public String file(){ return "/fileUploade"; }
引入fastdfs配置
import com.github.tobato.fastdfs.FdfsClientConfig; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableMBeanExport; import org.springframework.context.annotation.Import; import org.springframework.jmx.support.RegistrationPolicy; /** * 引入fastdfs配置 * Created huhu 1 on 2018/10/26. */ @Configuration @Import(FdfsClientConfig.class) @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) public class FdfsConfig { }
FastDFS客戶端包裝類
package com.gsafety.webmagic.visualize.common.wrapper; import com.github.tobato.fastdfs.domain.StorePath; import com.github.tobato.fastdfs.proto.storage.DownloadByteArray; import com.github.tobato.fastdfs.service.FastFileStorageClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.ByteArrayInputStream; import java.io.IOException; /** * FastDFS客戶端包裝類 * Created by hu on 2018/10/26. */ @Component public class FastDFSClientWrapper { private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class); @Autowired private FastFileStorageClient fastFileStorageClient; /** * 檔案上傳 * 最後返回fastDFS中的檔名稱;group1/M00/01/04/CgMKrVvS0geAQ0pzAACAAJxmBeM793.doc * * @param bytes 檔案位元組 * @param fileSize 檔案大小 * @param extension 副檔名 * @return fastDfs路徑 */ public String uploadFile(byte[] bytes, long fileSize, String extension) { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); StorePath storePath = fastFileStorageClient.uploadFile(byteArrayInputStream, fileSize, extension, null); System.out.println(storePath.getGroup() + "==" + storePath.getPath() + "======" + storePath.getFullPath()); return storePath.getFullPath(); } /** * 下載檔案 * 返回檔案位元組流大小 * @param fileUrl 檔案URL * @return 檔案位元組 * @throws IOException */ public byte[] downloadFile(String fileUrl) throws IOException { String group = fileUrl.substring(0, fileUrl.indexOf("/")); String path = fileUrl.substring(fileUrl.indexOf("/") + 1); DownloadByteArray downloadByteArray = new DownloadByteArray(); byte[] bytes = fastFileStorageClient.downloadFile(group, path, downloadByteArray); return bytes; } }
實現真正檔案上傳和下載
import com.gsafety.webmagic.visualize.common.wrapper.FastDFSClientWrapper; import com.gsafety.webmagic.visualize.service.DRFdfsUpAndDowService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLEncoder; /** * Created by 1 on 2018/10/26. */ @Service public class DRFdfsUpAndDowServiceImpl implements DRFdfsUpAndDowService{ @Autowired private FastDFSClientWrapper fastDFSClientWrapper; private final Logger logger = LoggerFactory.getLogger(DRFdfsUpAndDowServiceImpl.class); /** * 檔案上傳 * 最後返回fastDFS中的檔名稱;group1/M00/01/04/CgMKrVvS0geAQ0pzAACAAJxmBeM793.doc * @param file 頁面提交時檔案 * @return */ public String uploadFile(MultipartFile file){ byte[] bytes = new byte[0]; try { bytes = file.getBytes(); } catch (IOException e) { logger.error("獲取檔案錯誤"); e.printStackTrace(); } //獲取原始檔名稱 String originalFileName = file.getOriginalFilename(); //獲取檔案字尾--.doc String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1); String fileName = file.getName(); //獲取檔案大小 long fileSize = file.getSize(); System.out.println(originalFileName + "==" + fileName + "==" + fileSize + "==" + extension + "==" + bytes.length); return fastDFSClientWrapper.uploadFile(bytes, fileSize, extension); } /** * 檔案下載 * @param fileUrl 當前物件檔名稱 * @param response HttpServletResponse 內建物件 * @throws IOException */ public void downloadFile(String fileUrl, HttpServletResponse response) throws IOException { byte[] bytes = fastDFSClientWrapper.downloadFile(fileUrl); // 這裡只是為了整合fastdfs,所以寫死了檔案格式。需要在上傳的時候儲存檔名。下載的時候使用對應的格式 response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("sb.xlsx", "UTF-8")); response.setCharacterEncoding("UTF-8"); ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); outputStream.write(bytes); } catch (IOException e) { e.printStackTrace(); } finally { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
具體每個類對應的位置,在專案結構中已經有體現。
親測了沒毛病,非常簡單易懂,如果時新手,你可能要注意需要建立對應的資料庫存放上傳時檔案的名稱以便於在檔案下載的時候方便查詢。