This is the second small program development, mainly introduces how to upload pictures to Tencent cloud, Tencent cloud is chosen, because Tencent cloud free space big 😂

The preparatory work

Pictures are uploaded to Tencent Cloud Object Storage (COS).

To use the object storage API, perform the following steps:

  1. Purchase Tencent Cloud object Storage (COS) service
  2. Create a Bucket in the Tencent Cloud object Storage console
  3. Obtain the contents of AppID, SecretID, and SecretKey from the console personal API key page
  4. Write a request signing algorithm program (or use any of the server SDK)
  5. The signature is computed and the API is invoked to perform the operation

So the preparations we need to do are:

  • Enter Tencent cloud official website and register an account
  • Log in to the CLOUD object Storage Service (COS) console, enable the COS service, and create a Bucket for uploading resources
  • Configure the domain name information on the applet website (otherwise you cannot initiate a request for the domain name in the applet)
image

The configuration process will not be explained here, and steps 4 and 5 will be introduced next.

The process of uploading pictures to COS is as follows:

Picture uploading Flowchart

In this process, what we need to achieve is the steps of the authentication server to return the signature and the related steps of the small program.

COS authentication service

When the object storage service COS is used, HTTP anonymous requests or HTTP signature requests can be sent to COS through RESTful apis. For signature requests, the COS server authenticates the initiator of the request.

  • Anonymous request: An HTTP request does not carry any identity or authentication information and is implemented through RESTful apis.
  • Signature request: Add the signature during the HTTP request. COS server verifies the identity after receiving the message. If the authentication succeeds, the request can be accepted and executed; otherwise, error information will be returned and the request will be discarded. Tencent Cloud COS object storage implements identity Authentication based on the user-defined HTTP scheme of Hash Message Authentication Code (HMAC).

Uploading an image is a signature request that requires signature verification. The reason why we

The signature process

The customer signs the HTTP request and sends the signed request to Tencent Cloud for signature verification. The specific process is shown in the following figure.

The signature process

We use SDK development, this process is roughly understood, the implementation of the signature SDK has been included, just need to call the method.

From the signature process, we can know that signature requires SecretId and SecretKey, which are not suitable to be stored in the client, which is the main reason why we deploy an authentication server separately.

Signature generation API

As we described, the server generates the REST-API using the SANIC framework + Swagger_Py_codeGen.

Adding a signature generation API We need to add a description of the API to the documentation first. Document code: https://github.com/gusibi/Metis/blob/master/docs/v1.yml

    /qc_cos/config:
        get:
            summary: Tencent Cloud Configuration
            description: Tencent Cloud Configuration
            tags: [Config]
            operationId: get_qc_cos_config
            parameters:
                - $ref: '#/parameters/AccessToken'
                - $ref: '#/parameters/qcos_path_in_query'
            responses:
                200:
                    schema:
                        $ref: '#/definitions/QCOSConfig'
                default:
                    description: Unexpected error
                    schema:
                        $ref: '#/definitions/Error'
            security:
                - OAuth2: [open]Copy the code

This interface requires login to invoke. After the document definition is complete, call

swagger_py_codegen -s  docs/v1.yml . -p apis -tlp sanicCopy the code

Python from qcloud_cos.cos_auth import Auth

async def get(self, request):
    auth = Auth(appid=Config.QCOS_APPID,
                secret_id=Config.QCOS_SECRET_ID,
                secret_key=Config.QCOS_SECRET_KEY)
    expired = time() + 3600 The signature validity period is 3600 seconds
    Upload to the cos bucket directory
    dir_name = request.raw_args.get('cos_path'.'/xrzeti')
    # generate signature
    sign = auth.sign_more(Config.QCOS_BUCKET_NAME,
                          cos_path=dir_name,
                          expired=expired)
    return {"sign": sign}, 200Copy the code
> < p style = "max-width: 100%; clear: both; clear: both; [https://github.com/gusibi/cos-python-sdk-v4] (https://github.com/gusibi/cos-python-sdk-v4). Those using python3 can use this version.## Upload images to COS

### Select the image> 'wx.chooseImage(OBJECT)' selects pictures from the local album or takes pictures with the camera. By calling this method, the small program will put the selected picture into the temporary path (it can be used normally during the startup of the small program this time. If you need to keep it for a long time, you need to call wx.saveFile actively and can access it when the small program starts next time). We can only upload the files in the temporary path. Core code as follows: js uploadToCos:function() { var that = this; Wx. chooseImage({sizeType: [)'original'.'compressed'], // image type original compressed image, default both have success:function(res) {var file = res.tempFiles[0]; console.log(file.size); Var fileName = file.path.match(/(wxfile:\/\/)(.+)/) fileName = fileName[2] Specify a file name to upload to cos upload(file.path, fileName, that); }})}Copy the code

So once we’ve selected the image here, we’ll take the original image and upload it to cos.

To upload pictures

Cos The URL of the uploaded image is a combination of cos_region, appID, bucket_name, and cos_dir_name. Configure the following fields for your cos information, see the API documentation for details

cosUrl = "https://" + REGION + ".file.myqcloud.com/files/v2/" + APPID + "/" + BUCKET_NAME + DIR_NAME;Copy the code

REGION: cos Upload REGION APPID: APPID of the account BUCKET_NAME: name of the cos bucket DIR_NAME: directory of the uploaded file

var config = require('.. /config.js');
// Determine the URL to upload
var cosUrl = "https://" + config.cos_region + ".file.myqcloud.com/files/v2/" + config.cos_appid + "/" + config.cos_bucket_name + config.cos_dir_name;

// Enter your own authentication server address
var cosSignatureUrl = config.host + '/v1/qc_cos/config? cos_path=' + config.cos_dir_name;

/** * upload method * filePath: path of the uploaded file * fileName: fileName after uploading to cos * that: object */ of the current page where the small program resides
function upload(filePath, fileName, that) {
    var data;

    // Authenticate the signature
    wx.request({
        url: cosSignatureUrl,
        header: {
            Authorization: 'JWT' + ' ' + that.data.jwt.access_token
        },
        success: function (cosRes) {
            // Get the signature
            var signature = cosRes.data.sign;

            // Upload the file to COS with the signature in the header
            var uploadTask = wx.uploadFile({
                url: cosUrl + '/' + fileName,
                filePath: filePath,
                header: {
                    'Authorization': signature
                },
                name: 'filecontent'.formData: {
                    op: 'upload'
                },
                success: function (uploadRes) {
                    // Operation after successful upload
                    var upload_res = JSON.parse(uploadRes.data)
                    var files = that.data.files;
                    files.push(upload_res.data.source_url);
                    that.setData({
                        upload_res: upload_res,
                        files: files,
                        test_image: upload_res.data.source_url
                    })
                },
                fail: function (e) {
                    console.log('e', e)
                }
            });
            // Upload a progress bar
            uploadTask.onProgressUpdate((res) = > {
                that.setData({
                    upload_progress: res.progress
                })
                if (res.progress === 100){
                    that.setData({
                        upload_progress: 0})}})return data
}Copy the code

Small program provides uploadTask. OnProgressUpdate () to get photo upload progress, I will be here the upload progress shows out of the picture.

The complete code for reference: metis – wxapp: https://github.com/gusibi/Metis-wxapp

Refer to the link

  • Wecos-utric-demo — example of uploading COS for wechat applets user resources

Finally, thank your girlfriend for her support.

Welcome to follow (April_Louisa) Buy me a Fanta
Welcome to attention
Buy me a Fanta