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;
相关推荐
翼龙云_cloud9 小时前
亚马逊云服务器服务代理商:Bedrock 实践经验 Serverless 架构下的 AI 自动化落地
服务器·架构·serverless·云计算·aws
GPU实战笔记10 小时前
实例节点选择:创建入口与运行时稳定性的边界
云计算·a100·gpu 实例·节点选择·工作流验证
mengge.cloud16 小时前
1019Namespace ,Contexts ,Kubernetes Pod
运维·服务器·网络·云原生·容器·kubernetes·云计算
云老大-阿里云国际站代理商20 小时前
网站遇到恶意爬虫和CC攻击,阿里云国际站WAF与Bot管理怎么搭配
爬虫·阿里云·云计算
着迷不白1 天前
生产环境标准的Linux系统安装到服务器
linux·云计算
Geek-Chow2 天前
01 · Why AWS Lambda: Idle Cost, Capacity Planning and Risky In-Place Deploys
云计算
workflower2 天前
超算中心聚焦高性能计算场景(HPC)
大数据·网络·人工智能·机器人·云计算·汽车
workflower2 天前
Agentic AI 时代的企业ICT 基础设施运维
运维·人工智能·机器学习·重构·云计算·汽车
Geek-Chow3 天前
00 · AWS Lambda 心智模型学习指南:总览、思维导图与阅读路线(专栏目录)
云计算
Geek-Chow3 天前
07 · AWS Lambda 自测题与动手实验:用 AWS CLI 验证版本、别名、预置并发与冷启动
云计算