最近做了一个项目,项目生成的静态文件需要发送的cdn, 公司用的是百度云。我记录下流程
引入需要用到的包
const fs = require('fs')
const path = require('path')
const { BosClient }= require("@baiducloud/sdk");
通过fs 读取要上传的文件
let pathdir = path.resolve(__dirname, '../dist');
function getFiles(dir, files_) {
files_ = files_ || [];
let files = fs.readdirSync(dir); //同步的方向读取dir下的全部文件
for (let i in files) {
let name = dir + '/' + files[i];
if (fs.statSync(name).isDirectory()) {
getFiles(name, files_);
} else {
let obj = {};
obj.fullpath = name;
let path = name.replace(pathdir,'')
obj.path = publishPath.prefix + path
files_.push(obj);
}//是文件夹,继续遍历
}
return files_;
}
let files = getFiles(pathdir, []);
设置百度云的账号信息
let config = {
endpoint: "https://bj.bcebos.com",
credentials: {
ak: '',
sk: ''
}
};
let bucket = publishPath.bucket; // 设置容器名
let client = new BosClient(config);
遍历文件去实现上传
let uploads = files.map(fi => {
return new Promise((resolve,reject) => {
let fullpath = fi.fullpath
let data = fs.readFileSync(fi.fullpath);
let bufferData = new Buffer(data,'base64');
let filebuffer = Buffer.from(bufferData);
let fileSize = filebuffer.length;
let ext = fullpath.substring(fullpath.lastIndexOf(".") + 1);
let options = {
"content-length": String(fileSize), // 添加http header
"Content-Type": mimed[ext]
};
console.log(fi.path)
client.putObject(bucket, fi.path, filebuffer, options)
.then(response => resolve(fi.path)) // 成功
.catch(error => console.error('pp'));
})
})
bucket 是要上传文件的容器 在百度云配置 fi.path 是文件的路径 filebutter 是上传的文件
最后上传文件
Promise.all(uploads).then(res => console.log(res)).catch(err => console.log(err))