腾讯云文件上传 Token(Upload Token)是一种用于身份验证和授权的临时凭证,允许用户在腾讯云对象存储(COS)中上传文件。这个 Token 通常由服务端生成,并包含了一定的权限和有效期,确保只有获得 Token 的用户才能进行文件上传操作。
以下是一个简单的示例,展示如何在服务端生成一个上传 Token,并在客户端使用该 Token 上传文件到腾讯云 COS。
const COS = require('tencent-cloud-cos-nodejs-sdk-v5');
const cos = new COS({
SecretId: 'YOUR_SECRET_ID',
SecretKey: 'YOUR_SECRET_KEY',
});
app.get('/get-upload-token', (req, res) => {
const policy = {
version: '2.0',
statement: [{
action: ['name/cos:PutObject'],
effect: 'allow',
resource: ['qcs::cos:ap-guangzhou:uid/1250000000:examplebucket-1250000000/*'],
}],
};
const token = cos.auth.uploadToken('examplebucket-1250000000', null, 3600, policy);
res.json({ uploadToken: token });
});
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<input type="file" id="fileInput">
<script>
document.getElementById('fileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
fetch('/get-upload-token')
.then(response => response.json())
.then(data => {
const uploadToken = data.uploadToken;
const xhr = new XMLHttpRequest();
xhr.open("PUT", `https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/${file.name}`, true);
xhr.setRequestHeader("Authorization", uploadToken);
xhr.onload = function() {
if (xhr.status === 200) {
console.log('File uploaded successfully');
}
};
xhr.send(file);
});
});
</script>
</body>
</html>
问题:上传 Token 过期导致上传失败。 原因:Token 设置的有效期已过。 解决方法:
通过以上步骤,可以有效管理和使用腾讯云文件上传 Token,确保文件上传过程的安全与高效。
领取专属 10元无门槛券
手把手带您无忧上云