Home > Web Front-end > Front-end Q&A > Javascript implements oss signature

Javascript implements oss signature

WBOY
Release: 2023-05-12 13:18:07
Original
785 people have browsed it

When using Javascript to upload files to Alibaba Cloud OSS object storage service, you need to generate a signature for the request. This article will introduce how to use Javascript to implement OSS signature.

  1. Introducing SDK

First you need to introduce Alibaba Cloud's oss-sdk-js, which can be introduced through the following code:

<script src="//gosspublic.alicdn.com/aliyun-oss-sdk-6.6.5.min.js"></script>
Copy after login
  1. Initialize OSS Object

In the code, you need to use AK, SK and Endpoint to initialize the OSS object:

const client = new OSS({
  accessKeyId: 'YourAccessKeyId',
  accessKeySecret: 'YourAccessKeySecret',
  endpoint: 'YourEndpoint',
  bucket: 'YourBucketName'
})
Copy after login

Among them, YourAccessKeyId, YourAccessKeySecret, YourEndpoint and YourBucketName need to be replaced with those of the Alibaba Cloud account AK, SK, Endpoint and BucketName.

  1. Generate signature

Before uploading the file, you need to generate a signature for the request. The signature is generated as follows:

const sign = await client.signatureUrl('YourObjectName', {
  expires: 3600,  // 签名有效期,单位是秒
  method: 'PUT'   // 请求方法,可以是PUT或者POST
})
Copy after login

where YourObjectName is the uploaded file path. expires represents the validity period of the signature, which can be customized and the unit is seconds. method indicates the request method, which can be PUT or POST.

  1. File upload

After having the signature, file upload is implemented through JavaScript:

const file = document.querySelector('input[type=file]').files[0]
client.put('YourObjectName', file, {   
  progress: function* (p) {
    console.log('Progress:', p)
  }
}).then(r => {
    console.log('上传成功')
})
Copy after login

Among them, file is the file object and needs to be input[type =file] Get. YourObjectName indicates the uploaded file path, which needs to be consistent with the path in the signature. progress represents the callback function of upload progress.

At this point, the Javascript code to implement OSS signature is completed. You can use the above code to upload files to Alibaba Cloud OSS object storage service.

The above is the detailed content of Javascript implements oss signature. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template