用 Node.js 实现一个上传图片接口

初始化项目

在当前目录下创建一个名为 upload-image-api 的新文件夹,并初始化一个包含默认设置的 package.json 文件。

bash 复制代码
mkdir upload-image-api && cd upload-image-api
npm init -y

安装依赖

express 是一个流行的 Node.js Web 框架;multer 是一个用于处理文件上传的中间件。

bash 复制代码
npm install express multer

创建上传图片接口

在根目录下创建一个 index.js 入口文件,并实现简单的上传图片逻辑。

js 复制代码
const express = require("express");
const multer = require("multer");
const path = require("path");

const app = express();

// 设置存储路径和文件名称
const storage = multer.diskStorage({
  destination: path.join(__dirname, "uploads"),
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(
      null,
      file.fieldname + "-" + uniqueSuffix + path.extname(file.originalname)
    );
  },
});

// 创建文件上传中间件
const upload = multer({ storage: storage });

/**
 * 处理文件上传请求
 * upload.single('image') 函数中 `image` 为接收文件的参数名
 */
app.post("/upload", upload.single("image"), (req, res, next) => {
  if (!req.file) {
    return res.status(400).json({ error: "No file uploaded" });
  }

  const filePath = req.file.path;
  res.json({ filePath: filePath });
});

// 启动服务器
const port = 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

测试上传图片接口

  • 启动服务,在终端中执行命令:node index.js
  • 使用 Postman 或其他工具来测试图片上传接口。
  • http://localhost:3000/upload 发送 POST 请求,并以 multipart/form-data 格式附加一个名为 image 的字段来上传图片。
  • 如果请求成功,你将收到一个包含上传后的文件路径的 JSON 响应。
相关推荐
zhensherlock1 天前
Protocol Launcher 系列:Overcast 一键订阅播客
前端·javascript·typescript·node.js·自动化·github·js
Bigger1 天前
🚀 mini-cc:打造你的专属轻量级 AI 编程智能体
前端·node.js·claude
算是难了1 天前
TypeORM vs Prisma
数据库·typescript·node.js
xxjj998a1 天前
如何安装linux版本的node.js
linux·运维·node.js
青花瓷2 天前
Windows下Node.js的安装
node.js
暮雪倾风2 天前
【JS-Node】node.js环境安装及使用
开发语言·javascript·node.js
冴羽3 天前
请愿书:Node.js 核心代码不应该包含 AI 代码!
前端·javascript·node.js
太难了啊3 天前
从零构建你的 AI Agent 框架:Node.js 版 HelloAgents 实战指南
人工智能·node.js
网络点点滴3 天前
Node.js-构建模板
node.js
捉鸭子3 天前
海关总署瑞数vmp算法还原
python·网络安全·node.js·网络爬虫