使う前にexpressとali-ossのnpmでのインストールは忘れずに
const express = require('express');
const app = express();
const OSS = require('ali-oss');
//定义字符串内容
let str = 'Hello World! by Shin';
//把str转换成buffer
str = Buffer.from(str);
// 配置阿里云 OSS 客户端
const client = new OSS({
region: 'oss-cn-hongkong',
bucket: 'corpusmaker',
accessKeyId: "LTAI5tMdAL7XMobqcWDfEtR3",
accessKeySecret: "~~~~"
});
// 上传字符串到 OSS
async function saveToOSS(buffer, filename) {
try {
let result = await client.put(filename, buffer);
console.log('OSS File URL:', result.url);
return result.url;
} catch (error) {
console.error('Error uploading to OSS:', error);
throw error;
}
}
// 你可以在路由中调用这个函数
app.get('/', async (req, res) => {
//获取现在的时间
const now = new Date();
//把时间改为年月日时分秒的格式
const time = now.toISOString().replace(/[-:T.]/g, '');
//定义文件名
const filename = `${time}.txt`;
await saveToOSS(str, filename);
res.send('File uploaded to OSS');
});
const port = 3000;
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});