SpringBoot2.0整合Fastdfs

1.引入FastDfs依赖

<dependency>
   <groupId>com.github.tobato</groupId>
   <artifactId>fastdfs-client</artifactId>
   <version>1.26.2</version>
</dependency>

2.application.yml配置文件

fdfs:
  connect-timeout: 600
  so-timeout: 1500
  trackerList: 127.0.0.1:22122 
  thumb-image:  
    width: 150
    height: 150
  pool:
    max-total: 200

3.在启动类添加如下配置

@Configuration
@SpringBootApplication
@MapperScan("com.hxz.mapper")
@EnableMBeanExport(registration= RegistrationPolicy.IGNORE_EXISTING)
@Import(FdfsClientConfig.class)
@EnableAsync
public class BootApplication {
    public static void main(String[] args) {
        SpringApplication.run(BootApplication.class, args);
    }
}

4.controller 接口编写

package com.hxz.controller;


import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.velocity.shaded.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
/**
*@author hxz
*
*/
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 文件上传
     * @return result
     */
    @ResponseBody
    @PostMapping("/upload")
    public HashMap<String, Object> uploadImageByCover(MultipartFile attach){
        HashMap<String,Object> result = new HashMap<>();
        try {
            //上传
            StorePath path = fastFileStorageClient.
                            uploadFile(attach.getInputStream(),attach.getSize(),
                            FilenameUtils.getExtension(attach.getOriginalFilename()),null);
            //获取路径加名称
            String picName = path.getFullPath();
            result.put("msg",picName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 文件删除
     * @param path
     * @return
     */
    @DeleteMapping("/delete")
    public HashMap<String, Object> delete(@RequestParam String path) {
        HashMap<String,Object> result = new HashMap<>();
        // 第一种删除:参数:完整地址
        fastFileStorageClient.deleteFile(path);
        result.put("msg","恭喜恭喜,删除成功!");
        // 第二种删除:参数:组名加文件路径
        // fastFileStorageClient.deleteFile(group,path);

        return result;
    }


  /**
     * 文件下载
     * @param url 路径
     * @return
     */
    @GetMapping("/download")
    public void downLoad(@RequestParam String url, HttpServletResponse response) throws IOException {
        String group = url.substring(0, url.indexOf("/"));
        String path = url.substring(url.indexOf("/") + 1);
        //文件后缀
        String substring = url.substring(url.lastIndexOf(".") + 1);
        byte[] bytes = fastFileStorageClient.downloadFile(group, path, new DownloadByteArray());

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(UUID.randomUUID().toString()+"."+substring, "UTF-8"));

        // 写出
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.write(bytes, outputStream);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot并没有官方支持FastDFS集成,但是你可以通过引入相关的依赖和配置来实现Spring Boot与FastDFS整合。 首先,你需要引入FastDFS的客户端依赖。你可以在Maven或者Gradle的配置文件中添加以下依赖: Maven: ```xml <dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.29.0</version> </dependency> ``` Gradle: ```groovy implementation 'com.github.tobato:fastdfs-client:1.29.0' ``` 接下来,你需要配置FastDFS的连接信息。在Spring Boot的配置文件(application.properties或application.yml)中添加以下配置: ```properties # FastDFS连接信息 fdfs.connect-timeout=60000 fdfs.so-timeout=1500 fdfs.tracker-list=tracker_server1:port,tracker_server2:port ``` 其中,`fdfs.connect-timeout`表示连接超时时间,`fdfs.so-timeout`表示Socket超时时间,`fdfs.tracker-list`表示Tracker服务器的地址和端口。 然后,你可以创建一个FastDFS的工具类来进行上传和下载文件的操作。你可以参考以下示例代码: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import org.csource.fastdfs.*; import java.io.IOException; @Component public class FastDFSUtil { @Value("${fdfs.connect-timeout}") private int connectTimeout; @Value("${fdfs.so-timeout}") private int soTimeout; @Value("${fdfs.tracker-list}") private String trackerList; private TrackerClient trackerClient; private TrackerServer trackerServer; private StorageServer storageServer; private StorageClient storageClient; public FastDFSUtil() { try { ClientGlobal.setG_connect_timeout(connectTimeout); ClientGlobal.setG_network_timeout(soTimeout); ClientGlobal.setG_tracker_http_port(80); ClientGlobal.setG_anti_steal_token(false); ClientGlobal.setG_charset("UTF-8"); ClientGlobal.setG_secret_key(null); trackerClient = new TrackerClient(); trackerServer = trackerClient.getConnection(); storageServer = null; storageClient = new StorageClient(trackerServer, storageServer); } catch (Exception e) { e.printStackTrace(); } } public String uploadFile(MultipartFile file) { try { byte[] bytes = file.getBytes(); String originalFilename = file.getOriginalFilename(); String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); String[] uploadResults = storageClient.upload_file(bytes, extName, null); return uploadResults[0] + "/" + uploadResults[1]; } catch (Exception e) { e.printStackTrace(); } return null; } public byte[] downloadFile(String filePath) { try { String groupName = filePath.substring(0, filePath.indexOf("/")); String remoteFileName = filePath.substring(filePath.indexOf("/") + 1); return storageClient.download_file(groupName, remoteFileName); } catch (Exception e) { e.printStackTrace(); } return null; } } ``` 在上述代码中,`FastDFSUtil`类使用了Spring Boot的注解`@Component`,将其声明为一个Spring Bean。在该类的构造方法中,初始化了FastDFS的连接信息。`uploadFile`方法用于上传文件,`downloadFile`方法用于下载文件。 最后,你可以在你的Controller中注入`FastDFSUtil`,并使用它进行文件的上传和下载操作。 以上就是将Spring Boot与FastDFS整合的步骤。希望对你有帮助!如有更多疑问,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值