const qiniu = require('qiniu');
// 配置七牛云Access Key和Secret Key
const accessKey = 'your_access_key';
const secretKey = 'your_secret_key';
// 配置七牛云存储空间名称和域名
const bucket = 'your_bucket_name';
const domain = 'your_domain_name';
// 初始化七牛云SDK
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const config = new qiniu.conf.Config();
const formUploader = new qiniu.form_up.FormUploader(config);
const putExtra = new qiniu.form_up.PutExtra();
// 定义上传函数
function uploadFile(localFile, key) {
return new Promise((resolve, reject) => {
// 生成上传凭证
const options = {
scope: bucket + ':' + key,
};
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);
// 上传文件
formUploader.putFile(uploadToken, key, localFile, putExtra, function (err, body, info) {
if (err) {
reject(err);
} else {
resolve(domain + '/' + key);
}
});
});
}
// 调用上传函数上传文件
uploadFile('/path/to/local/file.jpg', 'test.jpg')
.then((url) => console.log('File uploaded:', url))
.catch((err) => console.error('File upload failed:', err));