1:添加依赖
注意:
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27.0.0</version>
</dependency>
2:配置config.conf 里面可以只配置tracker的地址和端口
tracker_server=192.168.0.180:221223:编写代码
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);
// 7、直接调用StorageClient对象方法上传文件即可。
URL url = new URL("http://a.hiphotos.baidu.com/image/pic/item/0e2442a7d933c895e97204b1d81373f0830200ef.jpg");//65536
// URL url = new URL("http://localhost:8080/dd/dddd.jpg");//65536
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
int fileLength = conn.getContentLength();//重要:网络文件的大小
//得到输入流
InputStream inputStream = conn.getInputStream();
NameValuePair[] metaList = new NameValuePair[3];
metaList[0] = new NameValuePair("fileName", "dddddd.jpg");
metaList[1] = new NameValuePair("fileExtName", "jpg");
metaList[2] = new NameValuePair("fileLength", String.valueOf(fileLength));
UploadFileSender us = new UploadFileSender(inputStream);
String[] strings = storageClient.upload_file(null,fileLength,us, "jpg", metaList);
for (String string : strings) {
System.out.println(string);
}
注意:
int fileLength = conn.getContentLength();//重要:网络文件的大小
网络io流和本地io流不同。网路io流inputStream.available();获取不了文件大小。返回值要比真实文件小。会报:
Connection reset by peer: socket write error错误
注意: 要设置文件大小。storageClient会根据大小来关闭输出流