NodeJs接入腾讯云存储COS

NodeJS接入

要在 Node.js 中接入腾讯云 COS(Cloud Object Storage),可以使用腾讯云 COS 的 Node.js SDK。以下是基本的接入步骤:

安装 COS SDK:首先,在您的 Node.js 项目中安装腾讯云 COS SDK。您可以使用 npm 或 yarn 进行安装:

复制代码
npm install cos-nodejs-sdk-v5

配置 COS 实例:在您的代码中,导入 COS SDK 并配置 COS 实例。您需要提供腾讯云的 SecretId、SecretKey、Bucket 名称等信息。以下是一个简单的示例:

复制代码
const COS = require('cos-nodejs-sdk-v5');
const cos = new COS({
     
     
    SecretId: 'yourSecretId',
    SecretKey: 'yourSecretKey',
});

使用 COS 服务

复制代码
const COS = require('cos-nodejs-sdk-v5');

const cos = new COS({
  SecretId: 'yourSecretId',
  SecretKey: 'yourSecretKey',
});

function getFileType(mimetype) {
  if (!mimetype) return 'unknown';
  if (mimetype.startsWith('image/')) return 'image';
  if (mimetype.startsWith('video/')) return 'video';
  if (mimetype.startsWith('audio/')) return 'audio';
  return 'file';
}

exports.uploadToCOS = (file, filename) => {
  return new Promise((resolve, reject) => {
    // 通过转码得到文件的中文名称
    const originalFilename = Buffer.from(filename, 'latin1').toString('utf8');
    const key = `uploads/${Date.now()}_${originalFilename}`;
    const type = getFileType(file.mimetype);

    cos.putObject(
      {
        Bucket: '桶名称',
        Region: '地址',
        Key: key,
        Body: file.buffer,
        ContentType: file.mimetype,
        ContentDisposition: 'inline',
      },
      (err, data) => {
        if (err) return reject(err);
        const url = `https://${data.Location}`;
        resolve({
          url,
          key,
          type,
          filename: originalFilename, // 这里仍然可以返回原始中文名供前端展示
        });
      }
    );
  });
};

接口路由:

复制代码
var express = require('express');
var router = express.Router();
const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage() }); // 用内存存文件
const { uploadToCOS } = require('../utils/cos');
router.post('/api/upload', upload.single('file'), async (req, res) => {
  try {
    const file = req.file;
    if (!file) return res.error('文件不能为空', 400);
    const fileData = await uploadToCOS(file, file.originalname);
    res.success(fileData, '上传成功');
  } catch (err) {
    console.error(err);
    res.error('上传失败', 400);
  }
});

module.exports = router;
相关推荐
AKAMAI12 小时前
当AI模型超出存储增长时
人工智能·云计算
Kendra91914 小时前
从 0 到上线:单文件网页 App 部署到阿里云 ECS 全流程(Nginx+Node+PM2+PostgreSQL)
nginx·阿里云·云计算·部署·个人开发·今天吃什么
北极糊的狐19 小时前
阿里云宝塔输入cat /www/server/panel/config/safe_path.conf报错 No such file or directory
阿里云·云计算
北极糊的狐21 小时前
阿里云宝塔报错bash tools/update.sh: No such file or directory 意思是:tools 整个目录直接丢失
阿里云·云计算·bash
NiceCloud喜云1 天前
阿里云 ECS 实例怎么选:面向出海业务的规格、地域与成本判断
阿里云·云计算
云老大-阿里云国际站代理商1 天前
腾讯云国际站代理商:CVM 跨地域网络抖动排查,深度分析 TCP 重传与 MTU 问题
网络·tcp/ip·腾讯云
丨晨 丨1 天前
LNMP_LAMP_项目实战教程
云计算
李小白661 天前
1-Shell编程和网络服务介绍
运维·云计算
zhougl9961 天前
Java实现腾讯云开发者社区列表爬虫
java·爬虫·腾讯云
yuhaiqun19891 天前
AI往哪长|云计算·边缘计算·世界模型·空间智能·具身智能一次讲透
人工智能·云计算·边缘计算·具身智能·世界模型·空间智能