如何使用 Node.js 實現(xiàn)一個上傳圖片接口
初始化項目
在當前目錄下創(chuàng)建一個名為 upload-image-api 的新文件夾,并初始化一個包含默認設(shè)置的 package.json 文件。
mkdir upload-image-api && cd upload-image-api npm init -y
安裝依賴
express 是一個流行的 Node.js Web 框架;multer 是一個用于處理文件上傳的中間件。
npm install express multer
創(chuàng)建上傳圖片接口
在根目錄下創(chuàng)建一個 index.js 入口文件,并實現(xiàn)簡單的上傳圖片邏輯。
const express = require("express");
const multer = require("multer");
const path = require("path");
const app = express();
// 設(shè)置存儲路徑和文件名稱
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)
);
},
});
// 創(chuàng)建文件上傳中間件
const upload = multer({ storage: storage });
/**
* 處理文件上傳請求
* upload.single('image') 函數(shù)中 `image` 為接收文件的參數(shù)名
*/
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 });
});
// 啟動服務(wù)器
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});測試上傳圖片接口
- 啟動服務(wù),在終端中執(zhí)行命令:
node index.js - 使用
Postman或其他工具來測試圖片上傳接口。 - 向
http://localhost:3000/upload發(fā)送POST請求,并以multipart/form-data格式附加一個名為image的字段來上傳圖片。 - 如果請求成功,你將收到一個包含上傳后的文件路徑的 JSON 響應(yīng)。
到此這篇關(guān)于用 Node.js 實現(xiàn)一個上傳圖片接口的文章就介紹到這了,更多相關(guān)Node.js 上傳圖片接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
nodejs發(fā)布靜態(tài)https服務(wù)器步驟指南
這篇文章主要為大家介紹了nodejs發(fā)布靜態(tài)https服務(wù)器的步驟指南,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-02-02
輕松創(chuàng)建nodejs服務(wù)器(10):處理POST請求
這篇文章主要介紹了輕松創(chuàng)建nodejs服務(wù)器(10):處理POST請求,本文告訴你如何實現(xiàn)在node.js中處理POST請求,需要的朋友可以參考下2014-12-12

