const qiniu = require('qiniu');
const fs = require('fs');
const path = require('path');
// 七牛云配置
const accessKey = 'accessKey';
const secretKey = 'secretKey-fNH9FejVul';
const bucket = 'bucket'; // 七牛云存储空间名
const filePath = './images' // 本地上传文件夹
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z1; // 选择对应的存储区域
const formUploader = new qiniu.form_up.FormUploader(config);
// 缓存刷新
const cdnManager = new qiniu.cdn.CdnManager(mac);
// 生成上传 Token
function uploadToken(bucket, key) {
const putPolicy = new qiniu.rs.PutPolicy({ scope: ${bucket}:${key}
});
return putPolicy.uploadToken(mac);
}
// 刷新缓存
function refreshFileCache(urls) {
return new Promise((resolve, reject) => {
// 提交刷新任务
cdnManager.refreshUrls(urls, (err, respBody, respInfo) => {
if (err) {
reject(err);
return;
}
if (respInfo.statusCode === 200) {
resolve(respBody);
} else {
reject(new Error(刷新失败: ${respInfo.statusCode}
));
}
});
});
}
// 上传单个文件到七牛云
function uploadFile(localFile, key) {
// 将文件的键(key)中的 = 替换为 =?
const modifiedKey = key
// const modifiedKey = key.split('=')[0] + '=' // 为了解决本地的文件名称存在?参数的问题,实际显示没有后续的一些参数
console.log("本地文件名称",localFile);
console.log("上传文件名称",modifiedKey);
// "MTcwMDA0NTA2NTczNzkyOTQ1NS5wbmc=?1700045065868.jpeg".split('=')[0] + '='
// 将 filename 属性设置为修改后的文件名 modifiedKey
// 上传重命名
let putExtra = new qiniu.form_up.PutExtra(modifiedKey);
putExtra.fname = modifiedKey;
return new Promise((resolve, reject) => {
const token = uploadToken(bucket, modifiedKey);
formUploader.putFile(token, modifiedKey, localFile, putExtra, async (err, body, info) => {
if (err) {
reject(err);
return;
}
if (info.statusCode === 200) {
// 上传成功后刷新缓存
await refreshFileCache([modifiedKey]);
resolve(body);
} else {
reject(new Error(`上传失败: ${info.statusCode}`));
}
});
});
}
// 读取并上传images目录下的所有文件
async function uploadImagesSequentially() {
try {
const files = fs.readdirSync(filePath);
for (const file of files) {
console.log(开始上传文件: ${file}
);
await uploadFile(${filePath}/${file}
, file);
console.log(https://cdn.hxdsmy.com/${file} 上传成功
);
}
console.log('所有文件上传完毕');
} catch (err) {
console.error('上传过程中出错:', err);
}
}
// 启动上传流程
uploadImagesSequentially();