nodejs mongodb 存储文件
时间: 2023-12-05 18:41:33 浏览: 87
以下是基于nodejs express mongodb multer实现的文件上传、存储、分页、管理功能的示例代码:
1.安装依赖
```shell
npm install express multer mongodb
```
2.引入依赖
```javascript
const express = require('express');
const multer = require('multer');
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId;
const url = 'mongodb://localhost:27017';
const dbName = 'fileUpload';
const upload = multer({ dest: 'uploads/' });
const app = express();
```
3.连接数据库
```javascript
MongoClient.connect(url, { useNewUrlParser: true }, function(err, client) {
if (err) throw err;
console.log("Connected successfully to server");
const db = client.db(dbName);
// ...
});
```
4.上传文件
```javascript
app.post('/upload', upload.single('file'), function(req, res, next) {
const file = req.file;
const collection = db.collection('files');
collection.insertOne(file, function(err, result) {
if (err) throw err;
res.send('File uploaded successfully!');
});
});
```
5.获取文件列表
```javascript
app.get('/files', function(req, res, next) {
const collection = db.collection('files');
const pageNum = parseInt(req.query.pageNum) || 1;
const pageSize = parseInt(req.query.pageSize) || 10;
const skip = (pageNum - 1) * pageSize;
collection.find().skip(skip).limit(pageSize).toArray(function(err, docs) {
if (err) throw err;
res.send(docs);
});
});
```
6.删除文件
```javascript
app.delete('/files/:id', function(req, res, next) {
const collection = db.collection('files');
const id = req.params.id;
collection.deleteOne({ _id: ObjectId(id) }, function(err, result) {
if (err) throw err;
res.send('File deleted successfully!');
});
});
```
阅读全文