【问题标题】:How to upload/save and show pictures with Mongoose,Express, Angular 4 and NodeJS如何使用 Mongoose、Express、Angular 4 和 NodeJS 上传/保存和显示图片
【发布时间】:2018-03-19 19:18:48
【问题描述】:

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

我应该使用插件吗?如果有,是哪一个?可以举个例子吗?

【问题讨论】:

    标签: node.js angular express mongoose


    【解决方案1】:

    如果你想上传文件到服务器,你可以使用 npm 提供的 multer module for nodejs。

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

    而且,如果您想将 multer 与 mongoose 一起使用,此示例也会有所帮助。

    Image.js

    import 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>
    

    【讨论】:

      猜你喜欢
      • 2017-02-10
      • 2011-07-06
      • 2013-03-24
      • 2020-03-22
      • 1970-01-01
      • 2018-12-31
      • 2020-06-28
      • 2018-12-16
      • 1970-01-01
      相关资源
      最近更新 更多