node 阿里云oss上传删除修改文件
在Node.js中使用阿里云OSS进行文件上传、删除和修改,首先需要安装阿里云官方提供的SDK:
npm install ali-oss
以下是使用阿里云OSS SDK进行上传、删除和修改文件的示例代码:
const OSS = require('ali-oss');
async function uploadFile() {
const client = new OSS({
region: '<Your region>',
accessKeyId: '<Your accessKeyId>',
accessKeySecret: '<Your accessKeySecret>',
bucket: '<Your bucket name>',
});
try {
// const result = await client.put('目标文件名', '本地文件路径');
const result = await client.put('object-key', 'local-file');
console.log(result);
} catch (e) {
console.error(e);
}
}
async function deleteFile() {
const client = new OSS({
region: '<Your region>',
accessKeyId: '<Your accessKeyId>',
accessKeySecret: '<Your accessKeySecret>',
bucket: '<Your bucket name>',
});
try {
const result = await client.delete('object-key');
console.log(result);
} catch (e) {
console.error(e);
}
}
async function modifyFile() {
const client = new OSS({
region: '<Your region>',
accessKeyId: '<Your accessKeyId>',
accessKeySecret: '<Your accessKeySecret>',
bucket: '<Your bucket name>',
});
try {
// 首先删除原有文件
await client.delete('object-key');
// 然后上传新文件
const result = await client.put('object-key', 'new-local-file');
console.log(result);
} catch (e) {
console.error(e);
}
}
// 调用函数
uploadFile(); // 上传文件
deleteFile(); // 删除文件
modifyFile(); // 修改文件