FastDFS上传文件一 : 单文件上传

FastDFS上传文件一 : 单文件上传

第一步 : 在src目录下fdfs_client.conf客户端配置文件

fdfs_client.conf配置文件代码如下

connect_timeout = 30
network_timeout = 30
charset = utf-8
http.tracker_http_port = 8888
http.anti_steal_token = no
http.secret_key = FastDFS1234567890

tracker_server = 192.168.56.109:22122
#tracker_server = 192.168.56.109:22122

第二步 : 添加配置信息到springmvc-console.xml文件

springmvc-console.xml文件中增加的配置bean代码如下




第三步 : 编写单文件上传的jsp代码


第四步 : 编写FastDFS工具类,做到通用性

/**
 * FastDFS工具类
 * 
 * @author Richard
 */
public class FastDFSTool {
    /**
     * 上传文件到FastDFS
     * 
     * @param bs
     *            文件字节数组
     * @param filename
     *            文件名
     * @return 上传成功后,存放在fastdfs中的文件位置及文件名
     * @throws FileNotFoundException
     * @throws IOException
     * @throws Exception
     */
    public static String uploadFile(byte[] bs, String filename)
            throws FileNotFoundException, IOException, Exception {
        // 获得classpath下文件的绝对路径
        ClassPathResource resource = new ClassPathResource("fdfs_client.conf");
       // 初始化客户端
        ClientGlobal.init(resource.getClassLoader()
                .getResource("fdfs_client.conf").getPath());

        // 创建老大客户端
        TrackerClient trackerClient = new TrackerClient();
        // 通过老大客户端取得连接获得老大服务器端
        TrackerServer connection = trackerClient.getConnection();
        // 小弟客户端
        StorageClient1 storageClient1 = new StorageClient1(connection, null);
        // 获得文件名的扩展名
        String extension = FilenameUtils.getExtension(filename);

        // 通过小弟客户端开始上传文件,并返回存放在fastdfs中的文件位置及文件名
        // 例如: group1/M00/00/00/wKg4ZViGbUOAWYBOAAFcP6dp0kY652.jpg
        String upload_file1 = storageClient1.upload_file1(bs, extension, null);

        return upload_file1;
    }
}

第五步 : 将FastDFS服务器地址编写到系统常量中

/**
 * 系统常量
 * 
 * @author Richard
 *
 */
public class Constants {
    /**
     * fastdfs服务器地址
     */
    public final static String FDFS_SERVER = "http://192.168.56.101:8888/";
}

第六步 : 编写单文件的代码

/**
 * 上传文件控制器
 * 
 * @author Richard
 *
 */
@Controller
public class UploadAction {

    // 上传单个文件
    @RequestMapping(value = "/uploadFile.do")
    @ResponseBody
    public HashMap uploadFile(MultipartFile mpf)
            throws FileNotFoundException, IOException, Exception {

        System.out.println(mpf.getOriginalFilename());

        // 将文件上传到分布式文件系统,并返回文件的存储路径及名称
        String uploadFile = FastDFSTool.uploadFile(mpf.getBytes(),
                mpf.getOriginalFilename());
        // 返回json格式的字符串(图片的绝对网络存放地址)
        HashMap hashMap = new HashMap();
        hashMap.put("path", Constants.FDFS_SERVER + uploadFile);
        return hashMap;
    }
}

你可能感兴趣的:(fastdfs上传大文件)