このチュートリアルは、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
を設定します
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 });
への[郵便]リクエストを使用する必要があります)。
<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に画像を保存するには、//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接続と画像処理ロジックをmongodb
に追加します。 (注:簡単にエラー処理と接続の詳細は省略されています。
npm install mongodb --save
server.js
および<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>
mongodb
この拡張されたチュートリアルは、node.jsアプリケーションでファイルのアップロードを処理するためのより完全で堅牢なソリューションを提供します。 コードを特定のニーズと環境に適応させることを忘れないでください。 プロダクションでファイルのアップロードを処理するときは、常にセキュリティのベストプラクティスに優先順位を付けてください。file-system
以上がnode.jsとexpressのMulterを使用してファイルアップロードしますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。