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.
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>
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' })
Among them, YourAccessKeyId, YourAccessKeySecret, YourEndpoint and YourBucketName need to be replaced with those of the Alibaba Cloud account AK, SK, Endpoint and BucketName.
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 })
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.
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('上传成功') })
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!