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     文件字节
     * @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 文件字节
     * @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 接口调用

@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();
            }
        }
    }

}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • springboot 概述 SpringBoot能够快速开发,简化部署,适用于微服务 参考嘟嘟大神SpringBo...
    一纸砚白阅读 10,923评论 2 20
  • https://github.com/cuzz1/springboot-learning 一、Spring Boo...
    cuzz_阅读 8,778评论 1 6
  • SpringBoot基础 学习目标: 能够理解Spring的优缺点 能够理解SpringBoot的特点 能够理解S...
    dwwl阅读 10,777评论 4 81
  • 一、SpringBoot简介 1.1 原有Spring优缺点分析 1.1.1 Spring的优点分析 Sprin...
    SingleXu阅读 9,838评论 1 20
  • 万万没想到做优弹素之后我最大的收获是这些 每天愈发觉得自己 又笨 又傻 又穷 别问我为什么,听听女剪子的策略,每一...
    小优1阅读 1,877评论 0 0

友情链接更多精彩内容