首页 > 技术文章 > coding++:java操作 FastDFS(上传 | 下载 | 删除)

codingmode 2019-07-04 16:43 原文

开发工具  IDEAL2017  Springboot 1.5.21.RELEASE

-------------------------------------------------------------------------------------

1、所需要的JAR文件

<!--IO-->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.2</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<!--FastDFS-->
<dependency>
    <groupId>org.csource</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27-SNAPSHOT</version>
</dependency>

 

2、fastdfs.properties 属性设置

#FastDFS配置begin-----------除了fastdfs.tracker_servers,其它配置项都是可选的
fastdfs.connect_timeout_in_seconds=5
fastdfs.network_timeout_in_seconds=30
fastdfs.charset=UTF-8
fastdfs.http_anti_steal_token=false
fastdfs.http_secret_key=FastDFS1234567890
fastdfs.http_tracker_http_port=80
fastdfs.tracker_servers=IP:22122
#FastDFS配置end-----------

3、操作工具类

package cn.com.soundrecording.utils;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

public class FastDFSClient {

    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageServer storageServer = null;
    private StorageClient1 storageClient = null;

    public FastDFSClient(String conf) throws Exception {
        if (conf.contains("classpath:")) {
            conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
        }
        ClientGlobal.initByProperties(conf);
        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageServer = null;
        storageClient = new StorageClient1(trackerServer, storageServer);
    }

    /**
     * 上传文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     *
     * @param fileName 文件全路径
     * @param extName  文件扩展名,不包含(.)
     * @param metas    文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
        String result = storageClient.upload_file1(fileName, extName, metas);
        return result;
    }

    public String uploadFile(String fileName) throws Exception {
        return uploadFile(fileName, null, null);
    }

    public String uploadFile(String fileName, String extName) throws Exception {
        return uploadFile(fileName, extName, null);
    }

    /**
     * 上传文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     *
     * @param fileContent 文件的内容,字节数组
     * @param extName     文件扩展名
     * @param metas       文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {

        String result = storageClient.upload_file1(fileContent, extName, metas);
        return result;
    }

    public String uploadFile(byte[] fileContent) throws Exception {
        return uploadFile(fileContent, null, null);
    }

    public String uploadFile(byte[] fileContent, String extName) throws Exception {
        return uploadFile(fileContent, extName, null);
    }

    /**
     * 下载文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     *
     * @param groupName 分组
     * @param remoteFileName  文件全路径名称
     * @return
     * @throws Exception
     */
    public byte[] download(String groupName,String remoteFileName)throws Exception{
        return storageClient.download_file(groupName, remoteFileName);
    }
    /**
     * 删除文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     *
     * @param groupName 分组
     * @param remoteFileName  文件全路径名称
     * @return
     * @throws Exception
     */
    public Integer delete(String groupName,String remoteFileName)throws Exception{
        int i = storageClient.delete_file(groupName, remoteFileName);
        return i;
    }

}

4、调用操作 后台代码

package cn.com.soundrecording.controller;

import cn.com.soundrecording.utils.FastDFSClient;
import com.sun.net.httpserver.HttpContext;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@RestController
public class UploedController {

    private final String URL = "http://wlkjs.cn/";

    //上传到服务器
    @PostMapping("/upload")
    @ResponseBody
    public String uploed(MultipartFile multipartFile, HttpServletRequest request) throws Exception {

        //文件类型
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //02、上传到服务器
        FastDFSClient dfsClient = new FastDFSClient("config/fastdfs.properties");
        String url = dfsClient.uploadFile(multipartFile.getBytes(), request.getParameter("type"));
        System.out.println(url);
        return URL + url;

    }

    //从服务器下载
    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse response) throws Exception {
        String name, groupName, remoteFileName;
        //初始化连接
        FastDFSClient dfsClient = new FastDFSClient("config/fastdfs.properties");
        //获取 group1 名称
        groupName = fileName.substring(fileName.indexOf("group1"), fileName.indexOf("/M00"));
        //获取 文件全路径 M00..xxxxx
        remoteFileName = fileName.substring(fileName.indexOf("M00"));
        name = fileName.substring(fileName.lastIndexOf("/"));
        //执行下载
        byte[] content = dfsClient.download(groupName, remoteFileName);
        //响应到客户端下载
        response.setContentType("application/ms-mp3;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                .concat(String.valueOf(URLEncoder.encode(name, "UTF-8"))));
        OutputStream out = response.getOutputStream();
        out.write(content);
        out.flush();
        out.close();
    }

    //从服务器删除
    @PostMapping("/delete")
    public Object delete(String fileName) throws Exception {
        String groupName, remoteFileName;
        //获取 group1 名称
        groupName = fileName.substring(fileName.indexOf("group1"), fileName.indexOf("/M00"));
        //获取 文件全路径 M00..xxxxx
        remoteFileName = fileName.substring(fileName.indexOf("M00"));
        //执行删除
        FastDFSClient dfsClient = new FastDFSClient("config/fastdfs.properties");
        //返回 0 代表成功
        int i = dfsClient.delete(groupName, remoteFileName);
        System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);
        return i;
    }

}

 

推荐阅读