记:demo------FastDFS实现文件下载 上传 删除

1.添加依赖:springboot实现


        org.springframework.boot
        spring-boot-starter-parent
        2.1.3.RELEASE

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
        
            net.sourceforge.nekohtml
            nekohtml
            1.9.22
        

        
        
            org.csource
            fastdfs-client-java
            1.27-SNAPSHOT
        
        
            org.projectlombok
            lombok
            1.16.20
        

        
            org.slf4j
            slf4j-api
        

        
            com.google.http-client
            google-http-client
            1.19.0
        
        
            fastdfs_client
            fastdfs_client
            1.25
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    7
                    7
                
            
        
    

2.配置文件 application.yml

server:
  port: 8081
spring:
  http:
    multipart:
      max-file-size: 30MB
      max-request-size: 40MB

3.配置文件 dfs.properties

#fastdfs核心配置
connect_timeout= 60
network_timeout= 60
charset= UTF-8
http.tracker_http_port= 8080
http.secret_key= 123456
http.anti_steal_token= false

#配置追踪服务器地址
tracker_server= 192.168.242.128:22122

4.前端页面1 upload.html




    
    FastDFS文件上传




4.前端页面1 status.html



FastDFS文件上传状态

![在这里插入图片描述]()

5.封装文件类

@Data
public class FastDFSFile {

    private String name;//文件名

    private String ext;//文件扩展名

    private byte[] content;//文件内容

    private String author;//文件作者

    public FastDFSFile(String name, String ext, byte[] content) {
        this.name = name;
        this.ext = ext;
        this.content = content;
    }

}

6.工具类

@Slf4j
public class FastDFSClientUtil {

    //初始化获取fdfs_client.conf配置文件路径
    static {
        try {
            String filePath = new ClassPathResource("fast_dfs.conf")
                    .getFile()
                    .getAbsolutePath();
            ClientGlobal.init(filePath);
        } catch (Exception e) {
            log.error("FastDFS Client 初始化失败!", e);
        }
    }

    //文件上传工具类
    public static String[] upload(FastDFSFile file) throws MyException {
        log.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);

        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] = new NameValuePair("author", file.getAuthor());

        String[] uploadResults = null;
        StorageClient storageClient = null;
        try {
            storageClient =getTrackerClient();
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (uploadResults == null && storageClient != null) {
            return null;
        }else{
            //String groupName = uploadResults[0];
            //String remoteFileName = uploadResults[1];
            //log.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
            return uploadResults;
        }
    }

    //获取追踪服务器url
    public static String getTrackerUrl() throws IOException {
        return "http://" + getTrackerServer().getInetSocketAddress().getHostString() + ":" + ClientGlobal.getG_tracker_http_port() + "/";
    }

    //获取追踪服务器客户端
    private static StorageClient getTrackerClient() throws IOException {
        TrackerServer trackerServer = getTrackerServer();
        return new StorageClient(trackerServer, null);
    }

    //获取追踪服务器
    private static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        return trackerClient.getConnection();
    }

    //获取文件的工具方法
    public static FileInfo getFile(String groupName, String remoteFileName) {
        try {
            StorageClient storageClient = getTrackerClient();
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //下载文件
    public static InputStream downFile(String groupName, String remoteFileName) {
        try {
            StorageClient storageClient = getTrackerClient();
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            return  new ByteArrayInputStream(fileByte);
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //删除文件
    public static void deleteFile(String groupName, String remoteFileName)
            throws Exception {
        StorageClient storageClient = getTrackerClient();
        int i = storageClient.delete_file(groupName, remoteFileName);
        log.info("delete file successfully!!!" + i);
    }

    //根据组名获取存储文件服务器
    public static StorageServer[] getStorageServerByGroupName(String groupName) throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getStoreStorages(trackerServer, groupName);
    }

    //获取文件服务器信息
    public static ServerInfo[] getServerInfo(String groupName,String remoteFileName) throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
    }
}

7.controller层

/**
 * 文件上传的接口
 */
@Controller
public class FastDFSComtroller {
   //跳转到文件上传界面
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String login(){

        return "upload";
    }

    //跳转到文件上传状态界面
    @RequestMapping(value = "/status",method = RequestMethod.GET)
    public String showStatus(){
        return "uploadStatus";
    }
    //跳转到下载界面
    @RequestMapping(value = "/down")
    public String showDownStatus(RedirectAttributes attributes){
        //调取下载方法 //http://192.168.242.128:8080/group1\M00/00/00/wKjygF0cthqAed8TAAEuu3TOhdw19.pptx
        String a ="group1";
        String b ="group1\\M00/00/00/wKjygF0cthqAed8TAAEuu3TOhdw19.pptx";//group1/M00/00/00/wKjygF0csvmAU6ACAAEy9XHDWws351.jpg
        InputStream path = FastDFSClientUtil.downFile(a,b);
        if (path != null) {
            attributes.addFlashAttribute("msg", "文件下载成功-->" );
            attributes.addFlashAttribute("path", path);
        }else{
            attributes.addFlashAttribute("msg", "文件下载失败");
        }
        return "redirect:status";
    }

    //文件上传接口
    @RequestMapping(value = "/upload")
    public String upload(@RequestBody MultipartFile file, RedirectAttributes attributes){
        if(file.isEmpty()){
            attributes.addFlashAttribute("msg","请选择您要上传的文件!!!!!");
            return "redirect:status";
        }
        //调取上传服务器的方法
        String path = uploadToServer(file);
        if (path != null) {
            attributes.addFlashAttribute("msg", "文件上传成功-->" + file.getOriginalFilename());
            attributes.addFlashAttribute("path", path);
        }else{
            attributes.addFlashAttribute("msg", "文件上传失败");
        }
        return "redirect:status";
    }

    //把文件上传到服务器
    private String uploadToServer(MultipartFile file){
        //获取文件的名字
        String originalFilename = file.getOriginalFilename();
        //获得文件的拓展名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("." )+ 1);

        try {
            byte[] content = file.getBytes();
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename,substring,content);
            String[] upload = FastDFSClientUtil.upload(fastDFSFile);
            if(upload!=null){
                return FastDFSClientUtil.getTrackerUrl() + upload[0] + File.separator + upload[1];
            }
        } catch (IOException e) {
            e.printStackTrace();
        }catch (MyException e) {
            e.printStackTrace();
        }
        return null;
    }

}

8.启动

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

9.项目结构
记:demo------FastDFS实现文件下载 上传 删除_第1张图片
上传结果:
记:demo------FastDFS实现文件下载 上传 删除_第2张图片

你可能感兴趣的:(FastDFS)