用 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 响应。
相关推荐
乐于分享的阿乐17 小时前
最新长期支持版本nodejs安装及环境配置(保姆级图文+安装包)
node.js
m0_5358175517 小时前
macOS上Claude Code安装配置保姆级教程:国内直连API,从0到1跑通(附避坑指南)
gpt·macos·ai·node.js·claude·claudecode·88api
五月君_19 小时前
放弃 Python,Kimi 用 TS + Node.js 重写了一个 Kimi Code
开发语言·python·node.js
涛声依旧-底层原理研究所21 小时前
Node.js在高并发低延迟场景中的优势
java·人工智能·python·node.js
晓杰'21 小时前
从0到1实现Balatro游戏后端(5):得分计算与单局结算流程实现
后端·typescript·node.js·游戏开发·项目实战·nestjs·webscoket
参宿71 天前
Shell 脚本语言(Bash/Sh)基础 与 应用
node.js
weifengma-wish1 天前
通过NPM安装claude code
前端·npm·node.js
不总是1 天前
Windows 系统 Node.js 免安装版(zip)安装与配置教程(2026 最新)
前端·windows·node.js
蓝乐2 天前
Express 知识点总结
node.js·express
kylinmin2 天前
Node.js安装及环境配置超详细教程(以win11为例子)
node.js