如何使用Mongoose,Express,Angular 4和NodeJS上传/保存和显示图片

我正在使用Mongoose,Express, Angular 4和NodeJS来创build一个应用程序,而且我对这个语言还很陌生。 在我的组件之一,我有一个CRUD,我想上传一张图片。 保存到Mongoose / MongoDB后,我想在屏幕上显示图片。

我应该使用插件吗? 如果是这样,哪一个? 你能举一个例子吗?

如果你想上传文件到服务器,你可以在npm中使用nodejs的multer模块。

这个网站将会对你非常有帮助。 – https://www.terlici.com/2015/05/16/uploading-files-locally.html

而且,如果你想使用mongoose,这个例子也将是有帮助的。

Image.js

 const mongoose from 'mongoose' const Schema = mongoose.Schema const Image = new Schema({ filename: { type: String, required: true }, originalname: { type: String, required: true } }, {timestamps: true}) module.exports = mongoose.model('Image', Image) 

server.js

 // ... const app = express() const Image = require('./Image.js') const multer = require('multer') const path = require('path') const UPLOAD_PATH = path.resolve(__dirname, 'path/to/uploadedFiles') const upload = multer({ dest: UPLOAD_PATH, limits: {fileSize: 1000000, files: 5} }) // upload image app.post('/api/image', upload.array('image', 5), (req, res, next) => { const images = req.files.map((file) => { return { filename: file.filename, originalname: file.originalname } }) Image.insertMany(images, (err, result) => { if (err) return res.sendStatus(404) res.json(result) }) }) // get image with id app.get('/:id', (req, res, next) => { Image.findOne({_id: req.params.id}, (err, image) => { if (err) return res.sendStatus(404) fs.createReadStream(path.resolve(UPLOAD_PATH, image.filename)).pipe(res) }) }) // ... 

client.js

 // ... const axios = require('axios') function uploadImage () { const files = document.getElementById('INPUT_TAG').files const formData = new FormData() formData.append('image', files[0]) axios.post('YOUR_URL/api/image', formData) } // ... 

upload.html

 <body> <input type="file" id="INPUT_TAG"/> <button>call uploadImage() with angular/vue/react/etc</button> </body> 

image.html

 <body> <img src="YOUR_URL/api/image/IMAGE_ID"> </body>