SpringBoot 引入 FastDFS

SpringBoot 引入 FastDFS

依賴

  • maven
<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.26.7</version>
</dependency>
  • 啟動類添加注解
@Import(FdfsClientConfig.class)
@SpringBootApplication
public class FdfsApplication {

    public static void main(String[] args) {
        SpringApplication.run(FdfsApplication.class, args);
    }

    /**
     * 處理上傳文件過大無法捕獲的異常
     * @return
     */
    @Bean
    public TomcatServletWebServerFactory tomcatEmbedded() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
            if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
                //-1 means unlimited
                ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
            }
        });
        return tomcat;
    }
}

工具類

@Component
public class FastDFSClientWrapper {

    private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class);
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 文件上傳
     *
     * @param bytes     文件字節(jié)
     * @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);
        return storePath.getFullPath();
    }

    /**
     * 下載文件
     *
     * @param fileUrl 文件URL
     * @return 文件字節(jié)
     * @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;
    }
}

配置

  • application.properties
# fastDFS 配置
fdfs.so-timeout=1501
fdfs.connect-timeout=601
fdfs.thumb-image.width=150
fdfs.thumb-image.height=150
fdfs.web-server-url=192.168.1.161
fdfs.trackerList[0]:192.168.1.161:22122

Web 接口調(diào)用

@Controller
public class FastDFSApi {

    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;

    /**
     * 訪問上傳頁面
     *
     * @return
     */
    @GetMapping("/")
    public String index() {
        return "upload";
    }

    /**
     * 返回信息
     *
     * @return
     */
    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "uploadStatus";
    }

    /**
     * 文件上傳
     *
     * @param file
     * @param redirectAttributes
     * @return
     * @throws IOException
     */
    @PostMapping("/uploaddata")
    public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadStatus";
        }
        byte[] bytes = file.getBytes();
        String originalFileName = file.getOriginalFilename();
        String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        String fileName = file.getName();
        long fileSize = file.getSize();
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded '" + file.getOriginalFilename() + "'");
        String path = fastDFSClientWrapper.uploadFile(bytes, fileSize, extension);
        redirectAttributes.addFlashAttribute("path",
                "file path url '" + path + "'");
        return "redirect:/uploadStatus";
    }

    /**
     * 文件下載
     *
     * @param fileUrl
     * @param fileName
     * @param response
     * @throws IOException
     */
    @RequestMapping("/download")
    public void downloadFile(String fileUrl, String fileName, HttpServletResponse response) throws IOException {
        byte[] bytes = fastDFSClientWrapper.downloadFile(fileUrl);
        // 這里只是為了整合fastdfs,所以寫死了文件格式。需要在上傳的時候保存文件名。下載的時候使用對應的格式
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "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();
            }
        }
    }

}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • springboot 概述 SpringBoot能夠快速開發(fā),簡化部署,適用于微服務 參考嘟嘟大神SpringBo...
    一紙硯白閱讀 5,741評論 2 20
  • https://github.com/cuzz1/springboot-learning 一、Spring Boo...
    cuzz_閱讀 3,552評論 1 6
  • SpringBoot基礎 學習目標: 能夠理解Spring的優(yōu)缺點 能夠理解SpringBoot的特點 能夠理解S...
    dwwl閱讀 5,513評論 4 81
  • 一、SpringBoot簡介 1.1 原有Spring優(yōu)缺點分析 1.1.1 Spring的優(yōu)點分析 Sprin...
    SingleXu閱讀 4,474評論 1 20
  • 萬萬沒想到做優(yōu)彈素之后我最大的收獲是這些 每天愈發(fā)覺得自己 又笨 又傻 又窮 別問我為什么,聽聽女剪子的策略,每一...
    小優(yōu)1閱讀 310評論 0 0

友情鏈接更多精彩內(nèi)容