node.js mongodb 上传图片
时间: 2023-11-16 13:01:45 浏览: 60
Node.js和MongoDB可以结合使用来实现图片上传功能。具体实现方法可以使用multer中间件来处理上传的文件,然后将文件存储到MongoDB数据库中。上传完成后,可以使用MongoDB的GridFS存储引擎来存储和管理大型文件,例如图片和视频等。同时,可以使用Vue.js等前端框架来实现图片预览和删除功能。
具体步骤如下:
```javascript
// 1. 安装multer和mongoose模块
npm install multer mongoose --save
// 2. 引入multer和mongoose模块
const multer = require('multer');
const mongoose = require('mongoose');
// 3. 配置multer中间件
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/') // 上传文件保存的路径
},
filename: function (req, file, cb) {
cb(null, file.originalname) // 上传文件保存的文件名
}
})
const upload = multer({ storage: storage })
// 4. 连接MongoDB数据库
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true });
// 5. 定义图片模型
const imageSchema = new mongoose.Schema({
name: String,
path: String
});
const Image = mongoose.model('Image', imageSchema);
// 6. 处理上传请求
app.post('/upload', upload.single('image'), function (req, res, next) {
const image = new Image({
name: req.file.originalname,
path: req.file.path
});
image.save(function (err) {
if (err) {
return res.status(500).send(err);
}
res.send('File uploaded successfully!');
});
});
// 7. 实现图片预览和删除功能
app.get('/images', function (req, res) {
Image.find({}, function (err, images) {
if (err) {
return res.status(500).send(err);
}
res.render('images', { images: images });
});
});
app.get('/images/:id', function (req, res) {
Image.findById(req.params.id, function (err, image) {
if (err) {
return res.status(500).send(err);
}
res.contentType(image.contentType);
res.send(image.data);
});
});
app.delete('/images/:id', function (req, res) {
Image.findByIdAndRemove(req.params.id, function (err, image) {
if (err) {
return res.status(500).send(err);
}
fs.unlink(image.path, function (err) {
if (err) {
return res.status(500).send(err);
}
res.send('File deleted successfully!');
});
});
});
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)