`

从零开始,在java中使用七牛云实现文件云存储(二)

阅读更多

在上一篇博客中,笔者简单介绍了从零开始,在java中使用七牛云实现文件的上传和下载。本章,笔者将介绍qiniu SDK的其他功能。

 

上篇文章的链接:从零开始,在java中使用七牛云实现文件云存储(一)

 

好了,直接进入正题,先介绍一下qiniu SDK的资源管理!

  1. 获取文件信息。就是获得已经上传到七牛云上的文件的详细信息,如上传时间、hash值、文件大小、类型等。直接上代码:
    	/**
    	 * 获取文件信息
    	 * @param zone
    	 * @param key
    	 * @param auth
    	 * @param bucket
    	 * @return
    	 */
    	public static FileInfo getFileInfo(Zone zone,String key,Auth auth,String bucket) {
    		// 构造一个带指定Zone对象的配置类
    		Configuration cfg = new Configuration(zone);
    		BucketManager bucketManager = new BucketManager(auth, cfg);
    		try {
    			FileInfo fileInfo = bucketManager.stat(bucket, key);
    			System.out.println(fileInfo.hash);
    			System.out.println(fileInfo.fsize);
    			System.out.println(fileInfo.mimeType);
    			System.out.println(fileInfo.putTime);
    			return fileInfo;
    		} catch (QiniuException ex) {
    			System.err.println(ex.response.toString());
    		}
    		return null;
    	}
     参数:key:要获取文件信息的文件名;bucket:你的存储空间名。其他两个参数在上一篇文章中介绍过,此处就不再说了。测试一下:
    public static void main(String[] args) {
    	getFileInfo(Zone.zone0(),"文件名",CredentialsManager.getAuth(),bucket);
    }
     注:getAuth()是我自己写的方法,用于生成身份凭证,在前一章中有介绍。

    可以看到控制台打印出了该文件的信息。

  2. 修改文件类型:
    	/**
    	 * 修改文件类型
    	 * @param zone
    	 * @param key
    	 * @param auth
    	 * @param bucket
    	 * @param newMimeType
    	 */
    	public static void editFileType(Zone zone,String key,Auth auth,String bucket,String newMimeType) {
    		// 构造一个带指定Zone对象的配置类
    		Configuration cfg = new Configuration(zone);
    		BucketManager bucketManager = new BucketManager(auth, cfg);
    		// 修改文件类型
    		try {
    			bucketManager.changeMime(bucket, key, newMimeType);
    		} catch (QiniuException ex) {
    			System.out.println(ex.response.toString());
    		}
    	}
    
    	public static void main(String[] args) {
    		
    		editFileType(Zone.zone0(), "要操作的文件名", CredentialsManager.getAuth(), bucket, "txt");
    	}
     前四个参数大家应该很熟悉了,最后一个参数newMimeType就是想要修改成的文件类型。

    例,先上传一个jpg文件,再用这个方法将该文件类型修改为txt,打开七牛控制管理台看看是不是修改成功了!

  3. 文件基本操作:删除、复制、移动。这三个操作大家再熟悉不过了吧,我们几乎每天都在做,此处将三个方法写在一起:
    	/**
    	 * 移动文件
    	 * @param zone
    	 * @param auth
    	 * @param fromBucket
    	 * @param fromKey
    	 * @param toBucket
    	 * @param toKey
    	 */
    	public static void move(Zone zone,Auth auth,String fromBucket,String fromKey,String toBucket,String toKey) {
    		// 构造一个带指定Zone对象的配置类
    		Configuration cfg = new Configuration(zone);
    		BucketManager bucketManager = new BucketManager(auth, cfg);
    		try {
    			bucketManager.move(fromBucket, fromKey, toBucket, toKey);
    		} catch (QiniuException ex) {
    			// 如果遇到异常,说明移动失败
    			System.err.println(ex.code());
    			System.err.println(ex.response.toString());
    		}
    	}
    
    	/**
    	 * 复制文件
    	 * @param zone
    	 * @param auth
    	 * @param fromBucket
    	 * @param fromKey
    	 * @param toBucket
    	 * @param toKey
    	 */
    	public static void copy(Zone zone,Auth auth,String fromBucket,String fromKey,String toBucket,String toKey) {
    		// 构造一个带指定Zone对象的配置类
    		Configuration cfg = new Configuration(zone);
    		BucketManager bucketManager = new BucketManager(auth, cfg);
    		try {
    			bucketManager.copy(fromBucket, fromKey, toBucket, toKey);
    		} catch (QiniuException ex) {
    			// 如果遇到异常,说明复制失败
    			System.err.println(ex.code());
    		}
    	}
    
    	/**
    	 * 刪除文件
    	 * @param key
    	 * @param auth
    	 * @param bucket
    	 */
    	public static void delete(Zone zone,String key,Auth auth,String bucket) {
    		// 构造一个带指定Zone对象的配置类
    		Configuration cfg = new Configuration(zone);
    		BucketManager bucketManager = new BucketManager(auth, cfg);
    		try {
    			bucketManager.delete(bucket, key);
    		} catch (QiniuException ex) {
    			// 如果遇到异常,说明删除失败
    			System.err.println(ex.code());
    			System.err.println(ex.response.toString());
    		}
    	}
    
    	public static void main(String[] args) {
    		delete(Zone.zone0(), "文件名", CredentialsManager.getAuth(), "Bucket");
    		move(Zone.zone0(),CredentialsManager.getAuth(),"fromBucket","fromKey","toBucket","toKey");
    		copy(Zone.zone0(),CredentialsManager.getAuth(),"fromBucket","fromKey","toBucket","toKey");
    	}
     参数:fromBucket:源存储空间;toBucket:目标存储空间;fromKey:源文件名;toKey:目标文件名。

    注:move()方法和Linux中的mv一样,可以用于修改文件名。

  4. 设置文件生存时间:
    	/**
    	 * 设置文件生存时间
    	 * @param zone
    	 * @param key
    	 * @param auth
    	 * @param bucket
    	 */
    	public static void setAliveTime(Zone zone,String key,Auth auth,String bucket,int days) {
    		// 构造一个带指定Zone对象的配置类
    		Configuration cfg = new Configuration(zone);
    		BucketManager bucketManager = new BucketManager(auth, cfg);
    		try {
    			bucketManager.deleteAfterDays(bucket, key, days);
    		} catch (QiniuException ex) {
    			System.err.println(ex.response.toString());
    		}
    	}
     说明:days:文件生存时间,单位(天)。该方法可以给文件设置生存时间或者给已经拥有生存时间的文件重新设置新的生存时间,当文件到达生存时间值时会被删除。
  5. 获取空间中的文件列表
    /**
    	 * 获取文件列表
    	 * @param zone
    	 * @param auth   授权凭证
    	 * @param bucket  存储空间名
    	 * @param prefix  文件名前缀
    	 * @param limit   每次迭代的长度限制,最大1000,推荐值 1000
    	 * @param delimiter  指定目录分隔符,列出所有公共前缀(模拟列出目录效果)。缺省值为空字符串
    	 * @return
    	 */
    	public static FileListIterator getFileList(Zone zone,Auth auth,String bucket,String prefix,int limit,String delimiter) {
    		// 构造一个带指定Zone对象的配置类
    		Configuration cfg = new Configuration(zone);
    		BucketManager bucketManager = new BucketManager(auth, cfg);
    		// 列举空间文件列表
    		BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit,
    				delimiter);
    		while (fileListIterator.hasNext()) {
    			// 处理获取的file list结果
    			FileInfo[] items = fileListIterator.next();
    			for (FileInfo item : items) {
    				System.out.println(item.key);
    				System.out.println(item.hash);
    				System.out.println(item.fsize);
    				System.out.println(item.mimeType);
    				System.out.println(item.putTime);
    				System.out.println(item.endUser);
    			}
    		}
    		return fileListIterator;
    	}	
    	public static void main(String[] args) {
    		getFileList(Zone.zone0(),CredentialsManager.getAuth(),"存储空间名","aaa",2,"");
    	}
     说明:上边这个main()方法的意思是列举出该存储空间中,所有以aaa开头的文件,每组2个结果。运行结果如下:
    aaa/10.jpg	FmTNr_WGx43QRT1NTuoerXdGsaIo	6316	image/jpeg	15136865517365207	null
    aaa/11.jpg	FtBTc2L4VwyRm56l_0tTHt_hoy4a	5623	image/jpeg	15136865583082726	null
    下一批:
    aaa/12.jpg	FuWyOfil3ZgwGnBANuHJ265ubed2	6319	image/jpeg	15136865626490302	null
    下一批:
     存储空间的文件列表如下:


     
     注意:文件名可以使用 前缀+文件名 的方式,就像放进了不同的路径一样,便于检索。
  6. 抓取网络上的文件,存入空间:
    	/**
    	 * 抓取网络资源到空间
    	 * @param zone
    	 * @param auth
    	 * @param bucket
    	 * @param key
    	 * @param remoteSrcUrl
    	 * @return
    	 */
    	public static FetchRet fetchToSpace(Zone zone,Auth auth,String bucket,String key,String remoteSrcUrl) {
    		// 构造一个带指定Zone对象的配置类
    		Configuration cfg = new Configuration(zone);
    		//String remoteSrcUrl = "http://devtools.qiniu.com/qiniu.png";
    		BucketManager bucketManager = new BucketManager(auth, cfg);
    		// 抓取网络资源到空间
    		try {
    			FetchRet fetchRet = bucketManager.fetch(remoteSrcUrl, bucket, key);
    			System.out.println(fetchRet.hash);
    			System.out.println(fetchRet.key);
    			System.out.println(fetchRet.mimeType);
    			System.out.println(fetchRet.fsize);
    			return fetchRet;
    		} catch (QiniuException ex) {
    			System.err.println(ex.response.toString());
    		}
    		return null;
    	}
    
    	public static void main(String[] args) {
    		fetchToSpace(Zone.zone0(),CredentialsManager.getAuth(),"存储空间名","test/qiniulogo","http://devtools.qiniu.com/qiniu.png");
    	}
    参数: remoteSrcUrl:网络资源的链接;key:给文件取个名字,如果设置成null,则存储的文件名默认设置成文件的hash值。

    七牛文件上传分为客户端上传(主要是指网页端和移动端等面向终端用户的场景)和服务端上传两种场景,服务端SDK在上传方面主要提供两种功能,一种是生成客户端上传所需要的上传凭证,另外一种是直接上传文件到云端。接下来介绍一下客户端上传凭证:

 

    客户端(移动端或者Web端)上传文件的时候,需要从客户自己的业务服务器获取上传凭证,而这些上传凭证是通过服务端的SDK来生成的,然后通过客户自己的业务API分发给客户端使用。根据上传的业务需求不同,七牛云Java SDK支持丰富的上传凭证生成方式。

 

 

private static String accessKey = "你的AK";
	private static String secretKey = "你的SK";
	private static String bucket = "你的存储空间名";
	
	public static Auth getAuth() {
		return Auth.create(accessKey, secretKey);
	}
	/**
	 * 生成上传凭证
	 */
	public static String getUploadCredential() {
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		System.out.println(upToken);
		return upToken;
	}

	/**
	 * 获取客户端覆盖上传凭证
	 * 
	 * @param fileKey 被覆盖的文件名
	 */
	public static String getOverloadCredential(String fileKey) {
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket, fileKey);
		System.out.println(upToken);
		return upToken;
	}
	
	
	/**
	 * 获取客户端上传凭证(自定义返回值)
	 * @param returnBody 自定义返回值
	 * @param expireSeconds 有效期(秒)
	 * @return
	 */
	public static String getUploadCredential(String returnBody,long expireSeconds) {
		Auth auth = Auth.create(accessKey, secretKey);
		StringMap putPolicy = new StringMap();
		putPolicy.put("returnBody",returnBody);
//		putPolicy.put("returnBody",
//				"{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
		String upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
		System.out.println(upToken);
		return upToken;
	}

	/**
	 *  获取客户端上传凭证(自定义回调application/json格式)
	 * 
	 * @param callbackBody 自定义回调
	 *            application/json格式
	 * @param callbackUrl 回调地址
	 * @param expireSeconds 有效期
	 */
	public static void getUploadCredential(String callbackBody, String callbackUrl,long expireSeconds) {
		Auth auth = Auth.create(accessKey, secretKey);
		StringMap putPolicy = new StringMap();
//		putPolicy.put("callbackUrl", "http://api.example.com/qiniu/upload/callback");
//		putPolicy.put("callbackBody",
//				"{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
		putPolicy.put("callbackUrl", callbackUrl);
		putPolicy.put("callbackBody",callbackBody);
		// putPolicy.put("callbackBody",
		// "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize),\"user\":\"$(x:user)\",\"age\",$(x:age)}");
		putPolicy.put("callbackBodyType", "application/json");
		String upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
		// String upToken = auth.uploadToken(bucket, key, expireSeconds, putPolicy,
		// false);//false:允许添加额外参数
		System.out.println(upToken);
	}

	/**
	 * 获取客户端上传凭证(自定义回调application/x-www-form-urlencoded格式)
	 * 
	 * @param callbackBody 自定义回调
	 *            application/x-www-form-urlencoded格式
	 * @param callbackUrl 回调地址
	 * @param expireSeconds 有效期
	 */
	public static void getUploadCredential2(String callbackBody, String callbackUrl,long expireSeconds) {
		Auth auth = Auth.create(accessKey, secretKey);
		StringMap putPolicy = new StringMap();
//		putPolicy.put("callbackUrl", "http://api.example.com/qiniu/upload/callback");
//		putPolicy.put("callbackBody", "key=$(key)&hash=$(etag)&bucket=$(bucket)&fsize=$(fsize)");
		putPolicy.put("callbackUrl", callbackUrl);
		putPolicy.put("callbackBody", callbackBody);
//		long expireSeconds = 3600;
		String upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
		System.out.println(upToken);
	}
	public static void main(String[] args) {
		getUploadCredential();
		getOverloadCredential("testfile");
		getUploadCredential("{\\\"key\\\":\\\"$(key)\\\",\\\"hash\\\":\\\"$(etag)\\\",\\\"bucket\\\":\\\"$(bucket)\\\",\\\"fsize\\\":$(fsize)}\"",3600);
		getUploadCredential("{\\\"key\\\":\\\"$(key)\\\",\\\"hash\\\":\\\"$(etag)\\\",\\\"bucket\\\":\\\"$(bucket)\\\",\\\"fsize\\\":$(fsize)}", "http://api.example.com/qiniu/upload/callback",3600);
		getUploadCredential2("key=$(key)&hash=$(etag)&bucket=$(bucket)&fsize=$(fsize)", "http://api.example.com/qiniu/upload/callback",3600);
	}
 以上的代码包含了基本的上传凭证生成方法,还有一个带有文件处理的凭证此处没做介绍,我会在以后的章节单独介绍。

 

说一下代码中的callbody和returnbody,这两个参数是由基本字符串和取值符$()组成的,$()支持系统变量自定义变量,若要详细了解请看官方文档。若要支持自定义变量,需要将uploadToke最后一个参数设置为false:

String upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy,false);
 若有此需求,需自行修改方法。

 

自定义的参数名称必须以x:开头。例如客户端上传的时候指定了自定义的参数x:userx:age分别是Stringint类型。那么可以通过下面的方式引用:

 

putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize),\"user\":\"$(x:user)\",\"age\",$(x:age)}");
 
putPolicy.put("callbackBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize),\"user\":\"$(x:user)\",\"age\",$(x:age)}");
 服务端处理自定义返回值时,可以自定义一个上传结果的返回值类putRet,用来解析返回的json字符串。

 

 

class MyPutRet {
    public String key;
    public String hash;
    public String bucket;
    public long fsize;
}
 
// 解析上传成功的结果
MyPutRet  putRet = new Gson().fromJson(response.bodyString(), MyPutRet .class);
 

 

今天先写到这,qiniu SDK的其他功能请期待

 

从零开始,在java中使用七牛云实现文件云存储(三)

  • 大小: 65.2 KB
1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics