覆盖和回调问题

时间:2018-09-25 15:52:39

标签: node.js vue.js multer

两天以来,当我在Vue Js上上传图像时,我试图解决一个问题。 一切都很好,除了我有一个空白的乡绅,其图片的网址很好,我需要刷新页面才能查看图片。就像是图像损坏或下载没有结束,然后我手动刷新。

我阅读了multer文档,检查了回调,但我不明白为什么会有这个问题。这是我服务器上的相关代码:

后端

const multer = require('multer')

const storage = multer.diskStorage({
    destination: '../client/static/images/uploads',
    filename: function (req, file, callback) {
        crypto.pseudoRandomBytes(16, function(err, raw) {
            if (err) return callback(err);
             callback(null, raw.toString('hex')+path.extname(file.originalname))
        });
    }
})
const upload = multer({storage:storage})

router.post('/uploadPic', upload.single('userPic'), function(req, res) {

    if (!req.file) {
        return res.send({success: false})
    } else {
        profile.addPic(req.body.id, req.body.isProfile, req.file.filename, callback => {
            var fs = require('fs');
            if (fs.existsSync('../client/static/images/uploads/'+req.file.filename)) {
                res.send({success: true})
            }
        })
    }
})

前端

第1步:我在组件上收集Formdata,完成后将数据发送到主要组件

upload () {
      this.feedback = ''
      var format = this.images.addFile.type

      function checkFormat (format) {
        switch (format) {
          case 'image/png': return true
          case 'image/jpeg': return true
          case 'image/jpg': return true
          default: return false
        }
      }
      function addFile (images, id, count, callback) {
        const formData = new FormData()
        formData.append('userPic', images, images.name)
        formData.append('id', id)
        if (!count) { formData.append('isProfile', 1) }
        callback(formData)
      }

      if (!checkFormat(format)) {
        this.feedback = 'Format de fichier invalide'
      } else if (this.images.count === 5) {
        this.feedback = 'Vous ne pouvez pas avoir plus de 5 photos'
      } else {
        addFile(this.images.addFile, this.userId, this.images.count, callback => {
          callback = this.$emit('updatePic', 'upload', callback)
        })
      }
    }

第2步:我收到了该事件,并且如果我上传了文件,则会进行切换,然后继续执行此功能,该功能将调用Front服务进行后面板和前面板之间的通信。

Pictures.uploadPic(data, callback => {
            callback = this.getPic(this.user.id)
          })

第3步:Pictures.uploadPic是一项与此相关的服务:

import Api from '@/services/Api'

export default {
  uploadPic (formData, callback) {
    return Api().post('profile/uploadPic', formData, callback).then(function (response) {
      callback(response.data)
    })
  },

更新 使用setTimeout我看到了问题。在将图像保存到文件中之前,我先放置了图像的路径。实际上,仅当我在路由器上传后输入Pic进入时,文件才保存在磁盘上。 Navin建议我使用multer中的next,但问题仍然相同。

router.post('/uploadPic', upload.single('userPic'), (req, res, next) => {
// my previous code to put in the db the pathname
}

0 个答案:

没有答案