打包静态文件上传到oss

64次阅读
没有评论

npm install ali-oss fs-extra

创建uploadToOSS.js,内容如下 ,执行node uploadToOSS.js

const fs = require('fs-extra');
const OSS = require('ali-oss');

const client = new OSS({
    region: 'oss-cn-shenzhen',
    accessKeyId: '',
    accessKeySecret: '',
    bucket: '',
    secure: true
});

const localDirectory = 'D:/vue-product/ceshi-vue3/dist';
const ossDirectory = 'upload/ceshi-dist';

const deleteEntireOSSDirectory = async (directory) => {
    // 列出Bucket下所有文件
    try {
        const result = await client.list({
            prefix: directory+'/', // 替换为你要删除的目录
        });

        const objects = result.objects.map(obj => ({
            key: obj.name,
        }));

        // 批量删除文件
        if (objects.length) {
            await client.deleteMulti(objects);
        }
    } catch (e) {
        console.error('Error:', e);
    }


};


const uploadFilesToOSS = async (localDir, ossDir) => {
    const files = fs.readdirSync(localDir);
    for (const file of files) {
        const filePath = `${localDir}/${file}`;
        const stats = fs.statSync(filePath);
        if (stats.isFile()) {
            await client.put(`${ossDir}/${file}`, filePath);
            console.log(`Uploaded file: ${file}`);
        } else if (stats.isDirectory()) {
            await uploadFilesToOSS(filePath, `${ossDir}/${file}`);
        }
    }
};

const run = async () => {
    try {
        await deleteEntireOSSDirectory(ossDirectory);
        await uploadFilesToOSS(localDirectory, ossDirectory);
        console.log('All files uploaded to OSS successfully.');
    } catch (error) {
        console.error('Error:', error);
    }
};

run();
正文完
 
评论(没有评论)