fastdfs文件上传java--根据本地io流上传

1:添加依赖
 
            net.oschina.zcx7878
            fastdfs-client-java
            1.27.0.0
        

2:配置config.conf  里面可以只配置tracker的地址和端口

tracker_server=192.168.0.180:22122
3:编写代码

3.1编写UploadFileSender 继承 UploadCallback。 其实:根据路径上传时,StorageClient也是根据路径,生成了UploadCallback的实现类:UploadBuff,这个类是StorageClient的静态内部类

class UploadFileSender implements UploadCallback {

    private InputStream inStream;

    public UploadFileSender(InputStream inStream) {
        this.inStream = inStream;
    }

    public int send(OutputStream out) throws IOException {
        byte[] bs = new byte[1024];
        int i=0;
        try{
            while ((i = inStream.read(bs)) != -1) {

                    out.write(bs, 0, i);
                
            }
            out.flush();
        }catch (Exception e){
            e.printStackTrace();
        }

        return 0;
    }
}
3.2:编写上传代码
 // 2、初始化全局配置。加载一个配置文件。
            ClientGlobal.init("client.conf");
            // 3、创建一个TrackerClient对象。
            TrackerClient trackerClient = new TrackerClient();
            // 4、创建一个TrackerServer对象。
            TrackerServer trackerServer = trackerClient.getConnection();
            // 5、声明一个StorageServer对象,null。
            StorageServer storageServer = null;
            // 6、获得StorageClient对象。
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            InputStream inputStream = new FileInputStream("e:/ceshi.html"); 
            int fileLength =inputStream.available();//获取文件大小
            NameValuePair[] metaList = new NameValuePair[3];
            metaList[0] = new NameValuePair("fileName", "ceshi.html");
            metaList[1] = new NameValuePair("fileExtName", "html");
            metaList[2] = new NameValuePair("fileLength", String.valueOf(fileLength));
            UploadFileSender us = new UploadFileSender(inputStream);
            String[] strings = storageClient.upload_file(null,fileLength,us, "html", metaList);
注意: 要设置文件大小。storageClient会根据大小来关闭输出流

你可能感兴趣的:(fastdfs文件上传java--根据本地io流上传)