Front-end upload files to Tencent Cloud (object storage)

Well, before I write it, I will briefly talk about why I want to write it. I still write this tutorial with a heavy heart, mainly because I don’t know if I can write it clearly, but since I have written a pen, it is hard Write it with your scalp, there is no way, after all, I finally figured it out after stumbling. There is also Baidu, and there is no tutorial, so I have strengthened my heart to write this blog post.

need analysis

Why do I upload the file to the server, it is very simple, the file is too large, the company's bandwidth is not enough, and it takes too long to upload a file, which leads to poor user experience, so how to solve this problem, a very effective solution is Upload the file to Alibaba Cloud or Tencent Cloud, and we can get the URL when we need it, which is the fastest.

Official API address

javaScript_SDK

Step Analysis

Since you want to use object storage, the first step is to buy this, otherwise how to use it? I won’t write about the process of buying. After all, I will not participate. After buying, I will briefly say the places that need to be configured:

The first thing to do is to apply for a bucket (storage bucket)



Click on one of them you need to use, this can be created several, I did not go into it, but it should be enough, and then the basic configuration:


Configure CORS

What needs to be said here? This is the configuration of CORS here, what is it doing here? When you submit the file, is the requested URL supported, if your URL is www.baidu.com? name=123&sex=nan, then whether your URl can be recognized by Tencent Cloud depends on whether this is configured in your CORS.

ok I suddenly remembered when I wrote this. In fact, after we purchase storage, Tencent Cloud will give you a series of field values:


These are what I will talk about in a while, don't worry about the fields here, the backend will handle it, explain what these do,

appleId is obviously used for identification

SecretId and SecretKey are used to generate the signature (I'll talk about that later)

Bucket and Region are used to identify regional information

download cos

Download js before using it:

npm i cos-js-sdk-v5 --save

How do we use these in the front end? If we are debugging, of course, it is best to generate the signature by ourselves, and then upload the file to Tencent Cloud, and Tencent Cloud will store the file after identification, but how does the front end generate the signature? It is also very simple, look at the code

Generate signature

var cos = new COS ({
	     SecretId: '********************************',
         SecretKey: '**************************',
		 })

COS is introduced in the API, it is a function of uploading files

This generates the signature

upload files

How to upload files?

Look at the code:

cos.putObject ({
		    Bucket: 'ky-********',  
		    Region: 'ap-shanghai',     
		    Key: name,
		    StorageClass: 'STANDARD',
		    Body: selectedFile, // upload file object
		    onProgress: function(progressData) {
		        console.log(JSON.stringify(progressData));
		    }
		}, function(err, data) {
		    console.log(err || data);
		    console.log(data.Location);
		});	
There is an introduction in the APi documentation
putObject // file upload, no more than 5G
Bucket //The following picture can be generated after the container is purchased is the corresponding relationship
Region //Can be set when purchasing a region

Key //File name
StorageClass //Storage method
Body //File object

Below is the log that prints the error message and success

So how do you get the file object here?

get file object

Look at the code:

	<input id="fileSelector" type="file" name="filename">
		<input id="submitBtn" type="button" onclick="test()" value="提交">
		<img src="" id="img0" class="img-thumbnail">
var selectedFile;	
	 var filename;
	 $("#fileSelector").change(function(){  
	 	     selectedFile = document.getElementById('fileSelector').files[0];
	 	     filename = selectedFile.name;
		});
selectedFile //File object

filename //file name  

This is actually very simple, it is to operate the dom to get the content of the file, and then get the name of the asking price

full code

The complete code is:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="../js/文件上传/cos-js-sdk-v5.js" type="text/javascript" charset="utf-8"></script>
		<script src="../js/jQuery/jquery-1.11.2.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	
	<body>
		<input id="fileSelector" type="file" name="filename">
		<input id="submitBtn" type="button" onclick="test()" value="提交">
		<img src="" id="img0" class="img-thumbnail">
	</body>
	<script type="text/javascript">
	 var selectedFile;	
	 var filename;
	 $("#fileSelector").change(function(){  
	 	     selectedFile = document.getElementById('fileSelector').files[0];
	 	     filename = selectedFile.name;
		});  
	 function test(){
		var cos = new COS ({
	     SecretId: 'AKIDwgAON63kfEZfV6rZR8anlUxBBwRhjOr4',
         SecretKey: '4sQijTxB9qHSN1OVMwGJ5bqoXzB7mCqI',
		 })
			cos.putObject ({
		    Bucket: 'ky-1254466590',  
		    Region: 'ap-shanghai',     
		    Key: filename,
		    StorageClass: 'STANDARD',
		    Body: selectedFile, // upload file object
		    onProgress: function(progressData) {
		        console.log(JSON.stringify(progressData));
		    }
		}, function(err, data) {
		    console.log(err || data);
		    console.log(data.Location);
		});	
	 }
	</script>
</html>

The above code is used for front-end debugging, that is, files can be uploaded to Tencent Cloud without a back-end

Principle of signature generation

If you are curious about how this signature is generated, you can look at the source code, this part:

// Signature algorithm description document: https://www.qcloud.com/document/product/436/7778
 // Step 1: Calculate SignKey
 var signKey = CryptoJS .HmacSHA1( qKeyTime , SecretKey ). toString ();

// Step 2: Form FormatString
 var formatString = [ method , pathname , obj2str ( queryParams ), obj2str ( headers ), '' ]. join ( ' \n ' );

// Step 3: Calculate StringToSign
 var stringToSign = [ 'sha1' , qSignTime , CryptoJS .SHA1( formatString ). toString (), '' ]. join ( ' \n ' );

// Step 4: Calculate Signature
 var qSignature = CryptoJS .HmacSHA1( stringToSign , signKey ). toString ();

// 步骤五:构造 Authorization
var authorization = ['q-sign-algorithm=' + qSignAlgorithm, 'q-ak=' + qAk, 'q-sign-time=' + qSignTime, 'q-key-time=' + qKeyTime, 'q-header-list=' + qHeaderList, 'q-url-param-list=' + qUrlParamList, 'q-signature=' + qSignature].join('&');
console.log("签名是:"+authorization);
return authorization;

verification process

https://www.qcloud.com/document/product/436/7778

Written in great detail, this is the flow chart:


success status


statusCode : 200 means the file was uploaded successfully

So does Tencent Cloud have this file?


Of course there is.

error code

All status codes will be returned. As long as they are incorrect, you can check the error status codes in the API. The error codes can solve the problems encountered very well.

If you upload it successfully, you can continue to read the following. If it fails, don't read it, because it is meaningless to read.

How to request the interface to get the signature and then complete the upload?

Under normal circumstances, it is not said that only the front-end operation is uploaded. Generally, the interface of the back-end is requested, and the upload operation is performed after the signature is obtained. How to operate at this time?

Upload with backend

request interface

Look at the code:

var cos = new COS ({
		   getAuthorization: function (options, callback) {
		        // Get the signature asynchronously
		        $.get('/user/getAutograph/'+filename, {
		            method: (options.Method || 'PUT').toLowerCase(),
		            pathname: '/' + (options.Key || '')
		        }, function (authorization) {
		            callback(authorization);
		        }, 'text');
		    }
		});

当然这里的filename您是可以不填的,这里我是以为需要做一个不重复名字才这样写的,这个名字是我用GUID生成以后处理的,GUID怎么生成这个,我之前写过,您可以找一下,避免出现上传重复文件的问题,腾讯云是上传重复文件的时候会覆盖掉,所以为了不丢数据,只能这样做。

还有一点就是上传的时候一般是需要预览的:


例如这样的,我之前写过预览的功能,您可以找一下

那么生成了签名以后,下面的步骤就和之前写的一样了,就不写重复代码了。

写到这里基本就完成了,但是相信您不是很明白,所以我也不知道怎么说可以说的更明白,只能哪里不明白您再问吧!


Guess you like

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