在node.js中使用multer上傳並上傳express
>該教程通過使用Node.js,Express和Multer構建文件上傳系統為您指導您。 我們將介紹單個和多個文件上傳,甚至演示在MongoDB數據庫中存儲圖像以進行以後的檢索。
首先,設置您的項目:
mkdir upload-express cd upload-express npm init -y npm install express multer mongodb file-system --save touch server.js mkdir uploads
登入後複製
>文件。 這將處理文件上傳和服務器邏輯。 最初,我們將設置一個基本的Express App:server.js
const express = require('express'); const multer = require('multer'); const app = express(); app.get('/', (req, res) => { res.json({ message: 'WELCOME' }); }); app.listen(3000, () => console.log('Server started on port 3000'));
登入後複製
處理文件上傳
//server.js (add this to your existing server.js) var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads') }, filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now()) } }); var upload = multer({ storage: storage });
登入後複製
>創建一個端點來處理單個文件上傳。 請記住,在您的
>中使用文件輸入創建一個相應的
(此處未顯示,但應使用post請求)。
<form></form>
index.html
>多個文件上傳/uploadfile
//server.js (add this to your existing server.js) app.post('/uploadfile', upload.single('myFile'), (req, res, next) => { const file = req.file; if (!file) { const error = new Error('Please upload a file'); error.httpStatusCode = 400; return next(error); } res.send(file); });
登入後複製
圖像上傳到mongodb
要將圖像存儲在MongoDB中,我們需要安裝
package://server.js (add this to your existing server.js) app.post('/uploadmultiple', upload.array('myFiles', 12), (req, res, next) => { const files = req.files; if (!files) { const error = new Error('Please choose files'); error.httpStatusCode = 400; return next(error); } res.send(files); });
登入後複製
請記住安裝
和mongodb
>軟件包。 還可以用數據庫名稱和連接字符串替換佔位符。 此改進的示例包括錯誤處理和異步操作以獲得更好的魯棒性。
npm install mongodb --save
登入後複製
server.js
>此增強教程為處理Node.js應用程序中的文件上傳提供了更完整,更強大的解決方案。 請記住將代碼適應您的特定需求和環境。 在處理生產中的文件上傳時,請始終優先考慮安全性最佳實踐。 <your_mongodb_connection_string></your_mongodb_connection_string>
以上是在node.js中使用multer上傳並上傳express的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章
<🎜>:種植花園 - 完整的突變指南
4 週前
By DDD
<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
1 個月前
By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
1 個月前
By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
4 週前
By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

在本週的平台新聞綜述中,Chrome引入了一個用於加載的新屬性,Web開發人員的可訪問性規範以及BBC Move
