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

时间:2017-10-08 13:59:56

标签: node.js angular express mongoose

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

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

1 个答案:

答案 0 :(得分:2)

如果要将文件上传到服务器,可以将multer模块用于npm提供的nodejs。

此网站对您非常有帮助。 - https://www.terlici.com/2015/05/16/uploading-files-locally.html

而且,如果你想使用mongoose multer,这个例子也会有所帮助。

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>