1
我正在使用Mongoose,Express,Angular 4和NodeJS來創建一個應用程序,而我對這種語言很陌生。 在我的一個組件中,我有一個CRUD,我想上傳一張圖片。 保存到Mongoose/MongoDB後,我想在屏幕上顯示圖片。如何使用Mongoose,Express,Angular 4和NodeJS上傳/保存和顯示圖片
我應該使用插件嗎?如果是這樣,哪一個?你能舉一個例子嗎?
我正在使用Mongoose,Express,Angular 4和NodeJS來創建一個應用程序,而我對這種語言很陌生。 在我的一個組件中,我有一個CRUD,我想上傳一張圖片。 保存到Mongoose/MongoDB後,我想在屏幕上顯示圖片。如何使用Mongoose,Express,Angular 4和NodeJS上傳/保存和顯示圖片
我應該使用插件嗎?如果是這樣,哪一個?你能舉一個例子嗎?
如果你想上傳文件到服務器,你可以在npm中使用nodejs的multer模塊。
本網站將對您非常有用。 - https://www.terlici.com/2015/05/16/uploading-files-locally.html
而且,如果你想使用mongo與貓鼬,這個例子也會有幫助。
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>