What is Object Storage OSS?

Object Storage Service (OSS), also known as object-based Storage, is a method to solve and deal with discrete units. It can provide data Storage services in the form of objects based on distributed systems. It has the characteristics of scalability, management and low cost, and supports central and edge Storage. It can realize the elastic scaling of storage requirements and is mainly applied to various scenarios of volume data management.

Why object storage?

As a new type of storage, what are the advantages of object storage? Why choose object storage? This may be a topic of concern to many businesses. To solve this puzzle, it might be useful to elaborate on several advantages of object storage:

  1. High reliability: The erasure code storage scheme provides better reliability. Copy redundancy across data centers ensures high service availability.

  2. Easy to expand: With object storage, there is no upper limit on storage space and no need to worry about expansion. Flexible scalability of storage requirements improves service flexibility.

  3. Low cost: No upfront investment. The convenience of using and paying for object storage on demand effectively avoids idle storage and bandwidth resources.

  4. Data intelligence: Closely collaborates with other products to provide standard HDFS access, providing a standard platform for massive high-speed read and write scenarios of big data and machine learning.

  5. Storage acceleration: Edge storage makes full use of available link bandwidth and speeds up data upload and download on edge nodes by over 60% on average.

  6. Edge computing: Edge computing and edge caching services are integrated nearby. Edge storage nodes have local data processing capabilities.

To sum up, just four words to save trouble and worry

Quick start

The premise condition

The cross-domain resource sharing (CORS) rule has been set. For details, see Setting Cross-Domain Access.

When the OSS is directly accessed through a browser, the CORS configuration requirements are as follows:

  • Source: Set to *.
  • Allow Methods: Select GET, POST, PUT, DELETE, and HEAD.
  • Allow Headers: set to *.
  • Expose Headers: Set the Headers to ETag, X-OSS-request-id, and X-OSS-version-id.

The STS temporarily grants access to the OSS

The cloud account AccessKey has the permission to access all apis. You are advised to authorize clients in STS mode. With STS, you can issue access credentials with custom timelines and permissions for third-party applications or subusers (that is, users whose identity is managed by you). For details, see STS Temporary Authorization to access OSS.

For details about how to use the browser, see Browser Applications.

See Example for an example project.

Use the SDK

Currently, bucket-related operations such as GetBucket (ListObjects), GetBucketLogging, and GetBucketReferer are not allowed in the browser. But it does allow you to perform object-related operations, such as PutObject, GetObject, and so on.

  • The introduction of the SDK
<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>
Copy the code

For other importing methods, see Installation details. Making through train

  • Obtain temporary STS authorization to access the OSS

I got it through Java, the front-end request interface

There are many, many more ways to get it

/** * Obtain aliYun login credentials, and add timer processing *@param {Object} UpdateForAliSts credentials store objects */
const UpdateForAliSts = {};
// Obtain the aliyun upload certificate
function proveForAli_pub() {
	let sts = JSON.parse(localStorage.getItem('sts'));
	if (sts) {
		let now = new Date().getTime();
		if (now - sts.timeout > 50 * 60 * 1000) {
			getAliSts();
		} else {
			let obj = JSON.parse(localStorage.getItem('sts')).data;
			UpdateForAliSts.accessKeyId = obj.accessKeyId;
			UpdateForAliSts.region = 'oss-cn-shanghai'; UpdateForAliSts.bucket = obj.bucketName; UpdateForAliSts.stsToken = obj.securityToken; UpdateForAliSts.accessKeySecret = obj.accessKeySecret; }}else{ getAliSts(); }}function getAliSts() {
	$.ajax({
		type: "post".url: adders + "/ly-manage/api/oss/getSTSCredentials".dataType: "json".xhrFields: { withCredentials: true },
		success: function (response) {
			if (response.succeed) {
				recentTime()
				response.timeout = new Date().getTime();
				UpdateForAliSts.accessKeyId = response.data.accessKeyId
				UpdateForAliSts.region = 'oss-cn-shanghai';
				UpdateForAliSts.bucket = response.data.bucketName;
				UpdateForAliSts.stsToken = response.data.securityToken;
				UpdateForAliSts.accessKeySecret = response.data.accessKeySecret;
				let str = JSON.stringify(response)
				localStorage.setItem('sts', str)
			} else {
				if (response.errCode == 403) {
					localStorage.removeItem('recentTime')
					document.location.href = '.. /.. /login.html';
				} else {
					$.message({
						type: 'error'.message: response.errMsg
					})
				}
			}
		}
	});
}
Copy the code
  • Upload a file

The multipartUpload interface is used to upload files. For details about multipartUpload, see Uploading fragments.

/** * Upload function *@param {string} Name Path name of the uploaded file *@param {object} The file file *@param {string} Key upload parameter object property *@param {string} Parmas Uploads parameter objects *@param {object} ClientData Ali Cloud certificate STS */
async function UploadPicturesForAli_pub(clientData, file, name, parmas, key) {
	let client = new OSS.Wrapper(UpdateForAliSts);
	let flieType = 'jpg';
	let contentType = 'image/jpeg';
	//... All images are converted to image/ JPEG
	if (file.type == 'image/gif') {
		flieType = 'gif';
		contentType = 'image/gif'
	} else if (file.type == 'video/mp4') {
		flieType = 'mp4';
		contentType = 'video/mp4'
	}
	// Save the picture in Ali Cloud path
	let storeName = `${name}/The ${new Date().getFullYear()}/${addZero(new Date().getMonth() + 1)}/${addZero(new Date().getDate())}/The ${new Date().getFullYear()
		+ addZero(new Date().getMonth() + 1) + addZero(new Date().getDate()) + addZero(new Date().getHours()) + addZero(new Date().getMinutes()) + addZero(new Date().getSeconds()) +
		addMinZroe(new Date().getMilliseconds()) + String(Math.random()).substr(2.8)}.${flieType}`;
	// Fragment upload
	await client.multipartUpload(storeName, file, { mime: contentType }, {
		progress: function* (percentage) {
			// Upload file progress
			let fileloadingNum = Math.ceil(percentage * 100) + The '%';
			console.log(fileloadingNum); 
		}
	}).then(res= > {
		// Add the path to the parameters submitted to the back end
		parmas[key] = '/' + res.name;
	});
}
Copy the code

What about uploading multiple files at the same time? Create a synchronous queue for asynchronous upload events? What would you do if it was you? Welcome to share your methods!! 🐱 🏍 🐱 🏍 🐱 🏍

videosArr.forEach(async function (item) {debugger
          if (item.type.split('/') [0] = ='video') {
                await UploadPicturesForAli_pub(clientDataVideo,'video-hall/videos/',item,'linkUrl',ajaxdata)
          }else{
                await UploadPicturesForAli_pub(clientData,'video-hall/thumbnails/',item,'coverPic',ajaxdata)
          }
 })
Copy the code
  • The download file

If security processing is performed, you need to use the signature URL to generate the download link of the file. You only need to click the link to download the file.

PS: Our company did not use the signature URL encryption processing in the early stage, which led to the Ali account being called overdue overnight. The signature URL is equivalent to creating a time-limited encrypted link, which will expire and become invalid.

// objectKey: file storage path saveAs: file access link
    let objectKey = 'video-hall/videos/2020/12/22/202012221550108671331333333.mp4';
    var client = new OSS.Wrapper(UpdateForAliSts)
    let saveAs = 'http://cdn.test.faceying.com/video-hall/videos/2020/12/22/202012221550108671331333333.mp4'
    let result = client.signatureUrl(objectKey, {
        expires: 3600.response: {
          'content-disposition': 'attachment; filename="' + saveAs + '"'}});console.log(result)
Copy the code

Combined with our company’s requirements, I wrote a function by the way

Refresh the table after uploading, and click to preview the picture/video information in the table

// Click the image/video zoom function used to format the image
template.defaults.imports.imgFormatEnlarge = function (value) {
	let result = ' ';
	if (value) {
		var disLength = value.length;
		var shortName = value.substring(disLength - 3, disLength);
		if (shortName == 'jpg') {
			result = value + '? x-oss-process=image/quality,q_60'
		} else if (shortName == 'mp4') {
			let index = value.lastIndexOf(".com");
			let objectKey = value.substring(index + 5, value.length);
			let client = new OSS.Wrapper(UpdateForAliSts);
			result = client.signatureUrl(objectKey, {
				expires: 3600.response: {
					'content-disposition': 'attachment; filename="' + value + '"'}}); }else {
			result = value
		}
		return result
	}
};
Copy the code
  • View the file list
let client = new OSS.Wrapper(UpdateForAliSts);
client.list({
    'max-keys': 10
  }).then(function (result) {
    console.log(result);
  }).catch(function (err) {
    console.log(err);
  });
Copy the code

Open the HTML file in your browser, and then open the Chrome Developer Tools to see the results of the listed files.

Ali Cloud and Qiniu Cloud for OSS object storage

Let’s talk about the two object stores I usually use, one is Ali, the other is Qiniuyun. Ali Cloud object storage is charged, the bill fee is composed of four parts

However, Qiniuyun will give users 10 GIGABytes of free storage space and charge extra fees for more than 10 gigabytes. Therefore, for ordinary users like us, 10 gigabytes of space is still sufficient for daily learning. But the premise is that you must have a domain name, through the domain name to register.

Generally, Aliyun is used to store the pictures, videos, documents and other files of the website blog, and Qiniuyun is used to store my photography pictures. Because of the large quantity, it is more cost-effective to save qiniuyun. There are still some small differences in the use of the two experience, such as Ali Cloud object storage background can create their own directory folder, storage of different types of files, and will automatically classify your blog system files by date

  • Finally, it is recommended to upload pictures/videos

Play with uploading videos

The wind and waves will sometimes, straight sail to the sea.

Come on together! Your likes are the biggest encouragement to me! 😁 😁 😁