From scratch, use Qiniu cloud to realize file cloud storage in java (2)

In the last blog, the author briefly introduced how to use Qiniu Cloud to upload and download files in java from scratch. In this chapter, the author will introduce other functions of qiniu SDK.

 

The link to the previous article: Starting from scratch, using Qiniu cloud to realize file cloud storage in java (1)

 

Ok, let’s go straight to the topic, let’s first introduce the resource management of qiniu SDK!

  1. Get file information. It is to get the detailed information of the files that have been uploaded to Qiniu Cloud, such as upload time, hash value, file size, type, etc. Go directly to the code:
    	/**
    	 * Get file information
    	 * @param zone
    	 * @param key
    	 * @param auth
    	 * @param bucket
    	 * @return
    	 */
    	public static FileInfo getFileInfo(Zone zone,String key,Auth auth,String bucket) {
    		// Construct a configuration class with the specified Zone object
    		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;
    	}
     Parameters: key: the file name to obtain the file information; bucket: the name of your storage space. The other two parameters were introduced in the previous article and will not be discussed here. have a test:
    public static void main(String[] args) {
    	getFileInfo(Zone.zone0(),"文件名",CredentialsManager.getAuth(),bucket);
    }
     Note: getAuth() is a method I wrote myself to generate credentials and was introduced in the previous chapter.

    You can see that the console prints out the information of the file.

  2. Modify file type:
    	/**
    	 * Modify the file type
    	 * @param zone
    	 * @param key
    	 * @param auth
    	 * @param bucket
    	 * @param newMimeType
    	 */
    	public static void editFileType(Zone zone,String key,Auth auth,String bucket,String newMimeType) {
    		// Construct a configuration class with the specified Zone object
    		Configuration cfg = new Configuration(zone);
    		BucketManager bucketManager = new BucketManager(auth, cfg);
    		// modify the file type
    		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);
	}
 The above code contains the basic upload certificate generation method, and a certificate with file processing is not introduced here, I will introduce it separately in later chapters.

 

Let's talk about callbody and returnbody in the code. These two parameters are composed of basic strings and value operators $(). $() supports system variables and custom variables . For details, please refer to the official documentation . To support custom variables, you need to set the last parameter of uploadToke to false:

String upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy,false);
 If you have this requirement, you need to modify the method yourself.

 

Custom parameter names must start with . For example, when the client uploads, the user-defined parameters and types are specified . Then it can be referenced in the following way:x:x:userx:ageStringint

 

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)}");
 When the server processes the custom return value, you can customize a return value class putRet of the upload result to parse the returned json string.

 

 

class MyPutRet {
    public String key;
    public String hash;
    public String bucket;
    public long fsize;
}
 
// Parse the result of successful upload
MyPutRet  putRet = new Gson().fromJson(response.bodyString(), MyPutRet .class);
 

 

I will write this first today, please look forward to other functions of the qiniu SDK

 

From scratch, use Qiniu cloud to realize file cloud storage in java (3)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326293146&siteId=291194637
Recommended