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

The advantages and disadvantages of Qiniu cloud storage are not discussed here, why should you choose it or something, only the usage method will be introduced, and we will go directly to the topic:

This article only introduces the implementation steps of using Qiniu Cloud as cloud storage, and does not introduce other functions of Qiniu Cloud (Live Cloud, CDN, etc.). To learn more, check out the official documentation:

 

Qiniu Cloud official documentation link

 

step:

Start from scratch↓

  1. The first step is to register a Qiniu account. Qiniu official website: www.qiniu.com.
  2. After registration, log in -> enter the control console -> select object storage -> create a new storage space -> fill in the form -> create complete


     
     instructions: the storage space name (Bucket) is globally unique, and the files in the public space can be directly used url access, but files in the private space need to add authorization credentials to the url before they can be accessed. The storage area and access control can be modified later, so there is no need to struggle with which one to choose.


     Once the storage space is established, you can store files in it. The following content will introduce how to interact with the storage space in java.

step:

  1. Import jar package. The official provides three introduction methods (the maven method used by the author, so the other two will not be introduced. If you want to know more, you can click here to view the official documentation). Add dependencies to pom:
    <dependencies>
        <dependency>
          <groupId>com.qiniu</groupId>
          <artifactId>qiniu-java-sdk</artifactId>
          <version>7.2.6</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>com.squareup.okhttp3</groupId>
          <artifactId>okhttp</artifactId>
          <version>3.3.1</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>com.google.code.gson</groupId>
          <artifactId>gson</artifactId>
          <version>2.6.2</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>com.qiniu</groupId>
          <artifactId>happy-dns-java</artifactId>
          <version>0.1.4</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
          <scope>test</scope>
        </dependency>
      </dependencies>
     
  2. To check your own Access Key and Secret Key, the method is as follows: Go to Qiniu Control Console -> Personal Center -> User Management, you can view AK (Access Key) and SK (Secret Key), and record these two values.
  3. The feature film is here, let’s put a code first, upload a picture and try it.
    	private static String accessKey = "Your AK";
    	private static String secretKey = "Your SK";
    	private static String bucket = "Your storage space name";
    	/**
    	 * Get upload certificate
    	 */
    	public static String getUploadCredential() {
    		Auth auth = Auth.create(accessKey, secretKey);
    		String upToken = auth.uploadToken(bucket);
    		System.out.println(upToken);
    		return upToken;
    	}
    
    
    	/**
    	 * File Upload
    	 * @param zone
    	 * East China Zone.zone0()
    	 * North China Zone.zone1()
    	 * South China Zone.zone2()
    	 * Kitami Zone.zoneNa0 ()
    	 * @param upToken upload certificate
    	 * @param localFilePath The local path of the file to be uploaded
    	 * @return
    	 */
    	public static DefaultPutRet fileUpload(Zone zone,String upToken,String localFilePath) {
    		// Construct a configuration class with the specified Zone object
    		Configuration cfg = new Configuration(zone);
    		// ...other parameters refer to class annotations
    		UploadManager uploadManager = new UploadManager(cfg);
    		// If the key is not specified by default, the hash value of the file content is used as the file name
    		String key = null;
    		try {
    			Response response = uploadManager.put(localFilePath, key, upToken);
    			// Parse the result of successful upload
    			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    			System.out.println(putRet.key);
    			System.out.println(putRet.hash);
    			return putRet;
    		} catch (QiniuException ex) {
    			Response r = ex.response;
    			System.err.println(r.toString());
    			try {
    				System.err.println(r.bodyString());
    			} catch (QiniuException ex2) {
    				// ignore
    			}
    		}
    		return null;
    	}
     Description: The above code has two methods, getUploadCredential() generates an upload credential based on ak, sk and bucket; fileUpload() implements file upload, and then introduces the parameters of fileUpload():

    zone: Each region corresponds to a zone object, and the corresponding relationship is as follows:

    	 * East China Zone.zone0()
    	 * North China Zone.zone1()
    	 * South China Zone.zone2()
    	 * Kitami Zone.zoneNa0 ()

    upToken: Credentials generated by getUploadCredential()

    localFilePath: The local path of the file to be uploaded, if it is a Linux environment, use something like "/home/qiniu/test.png"; if it is a Windows environment, use something like "D:\\qiniu\\test.png", note: characters There should be no spaces in the string, the author has been pitted by this.

    Return value: DefaultPutRet object, which contains the new file name and file hash value of the uploaded file.

  4. Write a main() to test the upload method above:
    	public static void main(String[] args) {
    		fileUpload(Zone.zone0(),CredentialsManager.getUploadCredential(),"D:\\qiniu\\test.jpg");
    	}
     Execute, open the Qiniu console -> object storage -> the space name you created -> content management, and see if your files are uploaded! !

     Isn't it strange that I haven't provided the url yet, so why did I upload it. That's right, Qiniu's SDK directly splices the url corresponding to your space through the globally unique bucket, so you only need to provide ak, sk and bucket to upload files.

However, in actual development, it is not enough to upload files. Let's introduce other functions of Qiniu SDK.

  1. Generate file download link. Of course, it is not enough to just upload the file. We have to find a way to access it. The following describes the methods for generating file download links in public space and private space. Without further ado, let’s go directly to the code:
    	private static String accessKey = "Your AK";
    	private static String secretKey = "Your SK";
    	private static String bucket = "Your storage space name";
    	
    	public static Auth getAuth() {
    		return Auth.create(accessKey, secretKey);
    	}
    	
    	/**
    	 * Public space returns the file URL
    	 * @param fileName
    	 * @param domainOfBucket
    	 * @return
    	 */
    	public static String publicFile(String fileName,String domainOfBucket) {
    		String encodedFileName=null;
    		try {
    			encodedFileName = URLEncoder.encode(fileName, "utf-8");
    		} catch (UnsupportedEncodingException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace ();
    		}
    		String finalUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
    		System.out.println(finalUrl);
    		return finalUrl;
    	}
    	
    	/**
    	 * Private space returns the file URL
    	 * @param auth
    	 * @param fileName
    	 * @param domainOfBucket
    	 * @param expireInSeconds
    	 * @return
    	 */
    	public static String privateFile(Auth auth,String fileName,String domainOfBucket,long expireInSeconds) {
    		String encodedFileName=null;
    		try {
    			encodedFileName = URLEncoder.encode(fileName, "utf-8");
    		} catch (UnsupportedEncodingException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace ();
    		}
    		String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
    		String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
    		System.out.println(finalUrl);
    		return finalUrl;
    	}
    	
    	public static void main(String[] args) {
    		publicFile("file name","your domainOfBucket");
    		//privateFile(CredentialsManager.getAuth(),"filename","your domainOfBucket",3600);
    	}
     Let's talk about the parameters: fileName: Yes, it is the key attribute in the returned DefaultPutRet object when uploading a file, which is the file name seen in the Qiniu console.

              domainOfBucket: The domain corresponding to your storage space can be viewed in the console, which is the one below.

     

     auth: The access credentials for the private space file, the value generated by getAuth()

     expireInSeconds: access link timeout time for private space files, unit (seconds)

     

     Execute it, paste the generated address directly in the browser, and see if the file can be accessed. This link is a fixed file connection, which can be placed in <img src=" "> in html (public space). Note that the address of the private space has a lifespan.

  2. Uploading files also supports byte stream, character stream upload and breakpoint resuming, just go to the code:
    /**
    	 * Character group upload
    	 * @param zone
    	 * @param upToken
    	 * @return
    	 */
    	public static DefaultPutRet charArrayUpload(Zone zone,String upToken) {
    		// Construct a configuration class with the specified Zone object
    		Configuration cfg = new Configuration(zone);
    		// ...other parameters refer to class annotations
    		UploadManager uploadManager = new UploadManager(cfg);
    		// If the key is not specified by default, the hash value of the file content is used as the file name
    		String key = null;
    		try {
    			byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
    
    			try {
    				Response response = uploadManager.put(uploadBytes, key, upToken);
    				// Parse the result of successful upload
    				DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    				System.out.println(putRet.key);
    				System.out.println(putRet.hash);
    				return putRet;
    			} catch (QiniuException ex) {
    				Response r = ex.response;
    				System.err.println(r.toString());
    				try {
    					System.err.println(r.bodyString());
    				} catch (QiniuException ex2) {
    					// ignore
    				}
    			}
    		} catch (UnsupportedEncodingException ex) {
    			// ignore
    		}
    		return null;
    	}
    
    	/**
    	 * Data stream upload
    	 * @param zone
    	 * @param upToken
    	 * @return
    	 */
    	public static DefaultPutRet streamUpload(Zone zone,String upToken) {
    		// Construct a configuration class with the specified Zone object
    		Configuration cfg = new Configuration(zone);
    		// ...other parameters refer to class annotations
    		UploadManager uploadManager = new UploadManager(cfg);
    		// ...generate upload credentials, then prepare to upload
    		// If the key is not specified by default, the hash value of the file content is used as the file name
    		String key = null;
    		try {
    			byte[] uploadBytes = "test streamUpload \n hello qiniu cloud".getBytes("utf-8");
    			ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
    			try {
    				Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
    				// Parse the result of successful upload
    				DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    				System.out.println(putRet.key);
    				System.out.println(putRet.hash);
    				return putRet;
    			} catch (QiniuException ex) {
    				Response r = ex.response;
    				System.err.println(r.toString());
    				try {
    					System.err.println(r.bodyString());
    				} catch (QiniuException ex2) {
    					// ignore
    				}
    			}
    		} catch (UnsupportedEncodingException ex) {
    			// ignore
    		}
    		return null;
    	}
    
    	/**
    	 * http
    	 * @param zone
    	 * @param upToken
    	 * @param localFilePath
    	 * @return
    	 */
    	public static DefaultPutRet breakPointUpload(Zone zone,String upToken,String localFilePath) {
    		// Construct a configuration class with the specified Zone object
    		Configuration cfg = new Configuration(zone);
    		// ...other parameters refer to class annotations
    		// If it is Windows, the format is D:\\qiniu\\test.png
    		// If the key is not specified by default, the hash value of the file content is used as the file name
    		String key = null;
    		String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), bucket).toString();
    		try {
    			// Set breakpoint resume file progress save directory
    			FileRecorder fileRecorder = new FileRecorder (localTempDir);
    			UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
    			try {
    				Response response = uploadManager.put(localFilePath, key, upToken);
    				// Parse the result of successful upload
    				DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
    				System.out.println(putRet.key);
    				System.out.println(putRet.hash);
    				return putRet;
    			} catch (QiniuException ex) {
    				Response r = ex.response;
    				System.err.println(r.toString());
    				try {
    					System.err.println(r.bodyString());
    				} catch (QiniuException ex2) {
    					// ignore
    				}
    			}
    		} catch (IOException ex) {
    			ex.printStackTrace();
    		}
    		// MyPutRet myPutRet=response.jsonToObject(MyPutRet.class);
    		return null;
    	}
    
    	
    	public static void main(String[] args) {
    		//fileUpload(Zone.zone0(),CredentialsManager.getUploadCredential(),"D:\\qiniu\\test.jpg");
    		//charArrayUpload(Zone.zone0(),CredentialsManager.getUploadCredential());
    		//streamUpload(Zone.zone0(),CredentialsManager.getUploadCredential());
    		breakPointUpload(Zone.zone0(),CredentialsManager.getUploadCredential(),"D:\\qiniu\\test.jpg");
    	}
     Did you notice the variable below,
    		// If the key is not specified by default, the hash value of the file content is used as the file name
    		String key = null;

    Yes, you can customize the file name when uploading a file. By default, the hash value is used as the file name. If you have this requirement, you can put the variable in the method parameter, like this:

    public static DefaultPutRet streamUpload(Zone zone,String upToken,String key) {
    
             //......
    
    }

     

 Well, 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 (2)

Guess you like

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