Dieses Tutorial führt Sie durch das Erstellen eines Datei -Upload -Systems mit Node.js, Express und Multer. Wir werden die Hoch- und mehrere Datei -Uploads behandeln und sogar das Speichern von Bildern in einer MongoDB -Datenbank zum späteren Abrufen demonstrieren.
Stellen Sie zunächst Ihr Projekt ein:
mkdir upload-express cd upload-express npm init -y npm install express multer mongodb file-system --save touch server.js mkdir uploads
Erstellen Sie als nächstes Ihre server.js
-Datei. Dadurch wird die Datei -Uploads und die Serverlogik behandelt. Zunächst richten wir eine grundlegende Express -App ein:
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'));
Konfigurieren wir Multer nun so konfigurieren
//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 });
mit einer Dateieingabe in Ihrem <form></form>
zu erstellen (hier nicht angezeigt, aber eine Postanforderung an 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); });
//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); });
-Paket installieren: mongodb
npm install mongodb --save
hinzu. (Hinweis: Fehlerbehandlungen und Verbindungsdetails werden für die Kürze weggelassen. Ersetzen Sie Platzhalter wie server.js
durch Ihre tatsächliche Verbindungszeichenfolge). <your_mongodb_connection_string></your_mongodb_connection_string>
const { MongoClient } = require('mongodb'); const fs = require('file-system'); // For file system operations // ... (previous code) ... const client = new MongoClient("<your_mongodb_connection_string>"); // ... (rest of your code) ... app.post('/uploadImage', upload.single('myImage'), async (req, res) => { try { await client.connect(); const db = client.db('your_database_name'); const imageBuffer = fs.readFileSync(req.file.path); const result = await db.collection('images').insertOne({ image: { filename: req.file.filename, buffer: imageBuffer } }); res.send(result); } catch (error) { console.error(error); res.status(500).send("Error uploading image"); } finally { await client.close(); } }); app.get('/photos', async (req, res) => { try { await client.connect(); const db = client.db('your_database_name'); const result = await db.collection('images').find().toArray(); const imgArray = result.map(element => element._id); res.send(imgArray); } catch (error) { console.error(error); res.status(500).send("Error retrieving images"); } finally { await client.close(); } }); app.get('/photo/:id', async (req, res) => { try { await client.connect(); const db = client.db('your_database_name'); const result = await db.collection('images').findOne({ _id: new ObjectId(req.params.id) }); res.contentType('image/jpeg'); // Adjust content type as needed res.send(result.image.buffer); } catch (error) { console.error(error); res.status(500).send("Error retrieving image"); } finally { await client.close(); } }); // ... (rest of your code) ...</your_mongodb_connection_string>
und mongodb
zu installieren. Ersetzen Sie auch Platzhalter durch Ihren Datenbanknamen und Ihre Verbindungszeichenfolge. Dieses verbesserte Beispiel beinhaltet Fehlerbehebung und asynchrone Operationen für eine bessere Robustheit. file-system
Das obige ist der detaillierte Inhalt vonDatei hochladen mit Multer in node.js und ausdrücken. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!