1. Introduction
The cloud is not a new concept. What exactly is the cloud? Even if you ask me to explain it clearly, I can’t explain it. For the time being, it is called the cloud if it is connected to the Internet. There are still many domestic cloud service providers, and there are two main categories. One is a host-like cloud provider similar to Alibaba Cloud, such as Wanwang and other traditional space providers; the other is application hosting. Platforms, such as BAE, SAE. Compared with space providers such as Alibaba Cloud, the entry level for application hosting platforms is lower, providing a good testing platform for the majority of struggling programmers.
The software upgrade program I was recently responsible for involved multiple platforms, multiple files, and multiple versions. If I built my own file server, the bandwidth would definitely not be able to meet business needs, so I started using the Baidu Cloud Storage BCS service. It works normally now, but the occasional intermittent convulsions forced me to Turning to Alibaba Cloud Storage, after all, commercial things still need to be commercialized and professional. At least if there is a problem, unlike Baidu Cloud Storage, the customer service cannot be found. But as a technical use, let’s talk about the use of cloud storage.
2. Usage steps
1. Register a Baidu account
I don’t need to say this.
2. Called a developer
Enter "Baidu Open Cloud Platform" (I don't know Baidu myself). If you are not a developer after logging in, you will be prompted to register as a developer. After filling in the information, it will be ok.
3. Create an application
Go to the Baidu Open Cloud homepage and create a BAE application engine. When creating, do not choose the solution: use BAE unless you still have a website to hang on. It's okay to give it a try. Then after entering, select cloud storage and create a Bucket (will be explained later).
4. Download SDK
5. Test code
3. Difficulties and Attentions
1. An SDK that does not have an API or does not have a detailed API requires a lot of energy to read, and it is not even as convenient as reading other people's blogs.
2. Understanding of concepts
Bucket: After creating an application, a Bucket will be created. What is a Bucket? Think of it as a drive letter under Windows, just like you create a D drive, where you can put files and folders. You can also Other Buckets can be created. It is actually inaccurate to say that Bucket is a drive letter because it is more like the root directory under Linux. When reading your file, you cannot say that my file is: 1.txt. Instead: /1.txt. Declared in the code.
Object: An Object represents a file. It consists of a lot of meta-information and file blocks (refer to the file system). The meta-information includes file name, file size, time, etc. Before using Object, be sure to remember "/";
3. Download authentication
Using http requests to download private files requires authentication parameters. If you read the official API, it only explains the encryption process of authorization, but there is no Java version. I will not specifically explain the authorization steps. I also provide the Java implementation. , because it has been implemented in the SDK, there is just a small problem. The "/" between the Bucket and the file name of the download address generated by the SDK is encoded, which will cause some downloaders to fail to download. For example, mobile QQ cannot download. Needs to be processed again.
4. API key and Secret Key
Access the app through this.
4. Detailed implementation
1. Guide package
2. Part of the code
Authorization:
Copy the code code as follows:
public class BCSHelper {
private String host = "";//Host name: bcs.duapp.com
private String accessKey = ""; //Can be seen in the application you create
private String secretKey = "";
private String bucket = "";//The name of the Bucket you created
private BaiduBCS baiduBCS = null;
public BCSHelper() {
this.host = Configuration.getHost();
this.accessKey = Configuration.getAccessKey();
this.secretKey = Configuration.getSecretKey();
this.bucket = Configuration.getBucket();
BCSCredentials credentials = new BCSCredentials(accessKey, secretKey);
baiduBCS = new BaiduBCS(credentials, host);
baiduBCS.setDefaultEncoding("UTF-8"); // Default UTF-8
}
Upload and delete files:
Copy the code code as follows:
/**
* Upload files to BCS
*
* @return boolean true indicates upload is successful
* @param file
* Files to be uploaded
*
*******/
public boolean putObject(File file) {
boolean result = true;
try {
//Must start with "/"
PutObjectRequest request = new PutObjectRequest(bucket, "/" + file.getName(), file);
//Set meta information of Object
ObjectMetadata metadata = new ObjectMetadata();
request.setMetadata(metadata);
baiduBCS.putObject(request);
LoggerService.addLoggerByOperate("BCS: Upload files to BCS:"+file.getName());
} catch (Exception e) {
result = false;
LoggerService.addLoggerByError(e.getMessage());
e.printStackTrace();
}
return result;
}
/**
* Delete files on BCS by Object name
*
* @param object
* Object name
* @return boolean true deletion successful
* *****/
public boolean deleteObject(String object) {
boolean result = true;
try {
if (existObject(object)) {
baiduBCS.deleteObject(bucket, "/" + object);
LoggerService.addLoggerByOperate("BCS: Delete files on BCS:"+object);
}
} catch (Exception e) {
result = false;
e.printStackTrace();
LoggerService.addLoggerByError(e.getMessage());
}
return result;
}
Determine whether Object exists:
Copy the code code as follows:
/**
* Determine whether the file exists in BCS
*
* @param object
* object name
* @return boolean true indicates existence
* ***/
public boolean existObject(String object) {
boolean result = false;
try {
result = baiduBCS.doesObjectExist(bucket, "/" + object);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Generate download address written by yourself:
Copy the code code as follows:
/**
* Get the download address of Object
*
* @param object
* Object name
* @return String Returns the downloaded url
*******/
public String getUrl(String object) {
// Content that needs to be encrypted
String data = "MBO" + "/n" + "Method=GET" + "/n" + "Bucket=" + bucket + "/n" + "Object=/" + object + "/n";
//Encrypted result
String hmacsha1 = getHmacSHA1(secretKey, data);
// Construct sign parameter
String sign = "MBO:" + accessKey + ":" + hmacsha1;
// url
StringBuilder builder = new StringBuilder();
builder.append("http://");
builder.append(host);
builder.append("/");
builder.append(bucket);
builder.append("/");
builder.append(object);
builder.append("?sign=");
builder.append(sign);
return builder.toString();
}
// Signature encryption
private String getHmacSHA1(String secretKey, String data) {
String result = "";
try {
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
Base64 base64 = new Base64();
@SuppressWarnings("static-access")
byte[] enbytes = base64.encodeBase64Chunked(rawHmac);
result = new String(enbytes, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Modified SDK generated address:
Copy the code code as follows:
* Get the download address of Object
*
* @param object
* Object name
* @return String Returns the downloaded url
*******/
public String getUrl(String object) {
String result = "";
GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(HttpMethodName.GET, bucket, "/" + object);
generateUrlRequest.setBcsSignCondition(new BCSSignCondition());
result = baiduBCS.generateUrl(generateUrlRequest);
result=result.replaceFirst("%2F", "/");
return result;
}
There are also a lot of test codes that have been provided by the official, and I have also provided them. If you need to, download them and study them yourself, and then encapsulate them and use them in actual projects. I have not found the progress of uploading files. I hope you can tell me what you see. , after all, he is also a rookie.