使用vuejs将图像上传到Nodejs Server无法正常工作

时间:2018-09-19 08:56:35

标签: node.js express file-upload vuejs2

将带有文本内容的表单数据从vuejs前端发送到Nodejs服务器,但是文件从未上传到服务器。我已经有一段时间了。这是我详细的前端和后端代码:

前端

//Front end VueJS

上传表单组件

<template>
<div class="container">
<form v-on:submit.prevent="addMember" method="post">

<div class="row">
   <div class="col-sm-10 col-md-10 col-lg-10">
       <div class="form-group">
            <label>Title<span class="required-field">*</span>:</label>
            <input type="text" class="form-control" v-model="member.title" name="title" v-validate="'required|min:10'">
            <div class="help-block alert alert-danger" v-show="errors.has('title')">
            {{errors.first('title')}}
            </div>

          </div>
   </div>
   </div>

   <div class="row">
   <div class="col-sm-10 col-md-10 col-lg-10">
       <div class="form-group">
            <label>Full Name<span class="required-field">*</span>:</label>
            <input type="text" class="form-control" v-model="member.fullname" name="fullname" v-validate="'required|min:10'">
            <div class="help-block alert alert-danger" v-show="errors.has('fullname')">
            {{errors.first('fullname')}}
            </div>

          </div>
   </div>
   </div>

   <div class="row">
   <div class="col-sm-10 col-md-10 col-lg-10">

       <div class="form-group">
              <label>Passport Photo
        <input type="file" id="file" ref="photo" v-on:change="handleFileUpload()"/>
      </label>           

      </div>
   </div>
   </div>

</form>

<div class="row">
   <div class="col-sm-10 col-md-10 col-lg-10">
    <div class="form-group">
 <button class="btn btn-info btn-lg pull-right">Save</button>
   </div>
   </div>
   </div>
   </div>
   </template>

   <script>
  export default {
  name:'CreateMember',

    data(){
        return{

            member:{},
            photo:'',
        }
    },



    },

    methods: {

        handleFileUpload(){
        this.coverimage = this.$refs.photo.files[0]
        },


 addMember(){

       this.$validator.validateAll().then(()=>
      {

      let formData = new FormData();
      formData.append('file', this.photo);
      let rawData = this.member
      rawData = JSON.stringify(rawData)
      formData.append('data',rawData)
     this.axios.post('/members',this.member,{
      'content-type':'multipart/form-data'
      }).then((resp)=>{
      console.log(resp.data)
      //this.$router.push({name: 'members'})

      }).catch((error)=>{
      console.log(error)
      })

    });

  }
  }
}
</script>

后端(Nodejs和Express)

**routes/members.js**

var express = require('express');
var router = express.Router();
//Require Controller Modules
var controller = require('../controllers/MembersController');
var auth = require('../middleware/auth');
const path = require('path');
const multer = require('multer');

//Define file storage engine
const storage = multer.diskStorage({

    destination:'public/uploads/',

    filename: (req,file,cb)=>{
      cb(null,file.fieldname+'-'+Date.now()+path.extname(file.originalname));
    }

  });
//Filter uploaded file and only upload file types of enumerated format
const fileTypeFilter = (req, file, cb)=>{
    if(file.mimetype==='image/jpeg'||file.mimetype==='image/jpg'|| file.mimetype==='image/png'){
        cb(null, true);

    }
    else{
    cb(new error('Invalid Image Format'), false);

    }
}
const upload = multer({storage:storage,
    limits:
    {
        fileSize:1024*1024*1000
    },

    filefilter:fileTypeFilter

});


//Save new member to the database
router.post('/members', upload.single('photo'),auth,controller.createMember);

Controllers/MembersController.js

var express = require('express');
var router = express.Router();
const fs = require('fs');
const Model = require('../models/index');
const Member = Model.sequelize.import('../models/member');

//createMember Controller Method

exports.createMember = function(req, res, next) {

        //Check if the cover image is attached
if(!req.file)
{
  return res.status(400).json({message:'Attach Photo!'}); //The request is returning this response, meaning the file is never uploaded. And the file actually is not being uploaded
}
     Member.create({
            title: req.body.title,
            fullname : req.body.fullname,
            photo : req.body.req.file.path           
        }).then(member=>{
          res.json(member);
        }).catch((error)=>{
          return res.json({status:500,error:error});
        });

        };

从请求中删除文件,其余数据按预期保存到数据库中

模型

//Models/member.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  var Member = sequelize.define('Member', {
    fullname: DataTypes.STRING,
    photo: DataTypes.STRING
  }, {});
  Member.associate = function(models) {
    // associations can be defined here
  };
  return Member;
};

可能做错了什么。上传目录为空。请帮帮我。

0 个答案:

没有答案