0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Node.jsで阿里云OSSにファイル保存 POSTでZIPを受けとる

Last updated at Posted at 2023-11-11

POSTされたファイル名をそのままアップロードできるよう修正しました。

const express = require('express');
const multer = require('multer');
const OSS = require('ali-oss');
const app = express();

const fs = require('fs');
const uploadDir = 'uploads/';

// 检查 uploads 目录是否存在,如果不存在则创建
if (!fs.existsSync(uploadDir)){
    fs.mkdirSync(uploadDir);
}


// 自定义 Multer 存储引擎,以保留原始文件名
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/');
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname); // 使用原始文件名
    }
});

// // 配置 Multer,用于存储上传的文件
// const upload = multer({ dest: 'uploads/' });

// 配置阿里云 OSS 客户端
const client = new OSS({
    region: 'oss-cn-hongkong',
    bucket: 'corpusmaker',
    accessKeyId: "LTAI5tMdAL7XMobqcWDfEtR3",
    accessKeySecret: "~~~~"
});
const upload = multer({ storage: storage });
// 上传文件到 OSS
async function saveFileToOSS(filePath, filename) {
    try {
        let result = await client.put(filename, filePath);
        console.log('OSS File URL:', result.url);
        return result.url;
    } catch (error) {
        console.error('Error uploading to OSS:', error);
        throw error;
    }
}

// 处理 POST 请求
app.post('/api/v1/save', upload.single('file'), async (req, res) => {
    if (!req.file) {
        return res.status(400).send('No file uploaded.');
    }

    try {
        // 上传文件到 OSS,并且文件名和原文件名一致
        const url = await saveFileToOSS(req.file.path, req.file.filename);
        res.send(`File uploaded to OSS: ${url}`);
    } catch (error) {
        res.status(500).send('Error uploading file to OSS.');
    }
});

const port = 3000
app.listen(port, () => {
    console.log(`App listening at http://localhost:${port}`);
});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?