Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Vuejs和Expressjs中上载文件_Javascript_Vue.js_Express_Multer - Fatal编程技术网

Javascript 如何在Vuejs和Expressjs中上载文件

Javascript 如何在Vuejs和Expressjs中上载文件,javascript,vue.js,express,multer,Javascript,Vue.js,Express,Multer,嘿,我是Vuejs和Express的新手…所以我正在尝试练习 因此,我试图创建一个用户配置文件,其中包含一个使用Vuejs和ExpressJs的图像,但没有上传任何文件或文本 这是我的CreateProfile.vue文件 <div class="icon-pic"> <label for="Password">Upload your Logo / Picture</label>

嘿,我是Vuejs和Express的新手…所以我正在尝试练习

因此,我试图创建一个用户配置文件,其中包含一个使用Vuejs和ExpressJs的图像,但没有上传任何文件或文本

这是我的CreateProfile.vue文件

       <div class="icon-pic">
       <label for="Password">Upload your Logo / Picture</label>
        <input type="file" ref="file" @change="handleFileUpload"/>
      </div>

      <b-input-group class="mb-2">
        <b-form-input
          id="input-small"
          type="text"
          placeholder="Enter your Name"
          required
          :rules="[rules.required]"
          v-model="profile.fullname"
        ></b-form-input>

        <b-form-input
          id="input-small"
          type="text"
          placeholder="Enter your BrandName"
          v-model="profile.brandname"
        ></b-form-input>
      </b-input-group>
const {Profile} = require ('../models')
const multer = require ('multer')

const fileFilter = (req, file, cb) => {
const allowedTypes = ["image/jpeg", "image/jpg", "image/png"]
if (!allowedTypes.includes(file.mimetype)){
const err = new Error('Incorrect File');
return cb(err, false)
}
cb(null, true)
}

const upload = multer ({
dest: '../public',
fileFilter,
})

module.exports = {
async post (req, res){
    try {
        upload.single('files')
        const profile = await new Profile({
        profile: this.profile,
        files: req.file
      });
      profile.save().then(result => {
        console.log(result);
        res.status(201).json({
          message: "Done upload!"
        })
      })
    } catch (err) {
        console.log(err)
        res.status(500).send({
        error: 'An Error has occured trying to fetch'
    })}}
module.exports = (sequelize, DataTypes) => {
const Profile = sequelize.define('Profile', {
     files: {
      type: DataTypes.JSON
     },
     fullname: {
       type: DataTypes.STRING,
       allowNull: false
     },
     brandname: DataTypes.STRING,
     skill1: DataTypes.STRING,
     skill2: DataTypes.STRING,
     skill3: DataTypes.STRING,
     skill4: DataTypes.STRING,
     socail_handle1: DataTypes.STRING,
     socail_handle2: DataTypes.STRING
 })
 return Profile 
 }
const AuthController = require('./controllers/AuthController')
const AuthControllerPolicy = require('./policies/AuthControllerPolicy')
const ProfileControler = require('./controllers/ProfileController')
const upload = require ('multer')

module.exports = (app) => {
app.post('/register',
    AuthControllerPolicy.register,
    AuthController.register)

app.post('/login',
    AuthController.login)

app.get('/profile',
    ProfileControler.index)
    
app.post('/upload', upload.single('file'),
    ProfileControler.upload)
然后是我的Model/Profile.js文件

       <div class="icon-pic">
       <label for="Password">Upload your Logo / Picture</label>
        <input type="file" ref="file" @change="handleFileUpload"/>
      </div>

      <b-input-group class="mb-2">
        <b-form-input
          id="input-small"
          type="text"
          placeholder="Enter your Name"
          required
          :rules="[rules.required]"
          v-model="profile.fullname"
        ></b-form-input>

        <b-form-input
          id="input-small"
          type="text"
          placeholder="Enter your BrandName"
          v-model="profile.brandname"
        ></b-form-input>
      </b-input-group>
const {Profile} = require ('../models')
const multer = require ('multer')

const fileFilter = (req, file, cb) => {
const allowedTypes = ["image/jpeg", "image/jpg", "image/png"]
if (!allowedTypes.includes(file.mimetype)){
const err = new Error('Incorrect File');
return cb(err, false)
}
cb(null, true)
}

const upload = multer ({
dest: '../public',
fileFilter,
})

module.exports = {
async post (req, res){
    try {
        upload.single('files')
        const profile = await new Profile({
        profile: this.profile,
        files: req.file
      });
      profile.save().then(result => {
        console.log(result);
        res.status(201).json({
          message: "Done upload!"
        })
      })
    } catch (err) {
        console.log(err)
        res.status(500).send({
        error: 'An Error has occured trying to fetch'
    })}}
module.exports = (sequelize, DataTypes) => {
const Profile = sequelize.define('Profile', {
     files: {
      type: DataTypes.JSON
     },
     fullname: {
       type: DataTypes.STRING,
       allowNull: false
     },
     brandname: DataTypes.STRING,
     skill1: DataTypes.STRING,
     skill2: DataTypes.STRING,
     skill3: DataTypes.STRING,
     skill4: DataTypes.STRING,
     socail_handle1: DataTypes.STRING,
     socail_handle2: DataTypes.STRING
 })
 return Profile 
 }
const AuthController = require('./controllers/AuthController')
const AuthControllerPolicy = require('./policies/AuthControllerPolicy')
const ProfileControler = require('./controllers/ProfileController')
const upload = require ('multer')

module.exports = (app) => {
app.post('/register',
    AuthControllerPolicy.register,
    AuthController.register)

app.post('/login',
    AuthController.login)

app.get('/profile',
    ProfileControler.index)
    
app.post('/upload', upload.single('file'),
    ProfileControler.upload)
我希望任何人都能帮助我,请

这是我的route.js文件

       <div class="icon-pic">
       <label for="Password">Upload your Logo / Picture</label>
        <input type="file" ref="file" @change="handleFileUpload"/>
      </div>

      <b-input-group class="mb-2">
        <b-form-input
          id="input-small"
          type="text"
          placeholder="Enter your Name"
          required
          :rules="[rules.required]"
          v-model="profile.fullname"
        ></b-form-input>

        <b-form-input
          id="input-small"
          type="text"
          placeholder="Enter your BrandName"
          v-model="profile.brandname"
        ></b-form-input>
      </b-input-group>
const {Profile} = require ('../models')
const multer = require ('multer')

const fileFilter = (req, file, cb) => {
const allowedTypes = ["image/jpeg", "image/jpg", "image/png"]
if (!allowedTypes.includes(file.mimetype)){
const err = new Error('Incorrect File');
return cb(err, false)
}
cb(null, true)
}

const upload = multer ({
dest: '../public',
fileFilter,
})

module.exports = {
async post (req, res){
    try {
        upload.single('files')
        const profile = await new Profile({
        profile: this.profile,
        files: req.file
      });
      profile.save().then(result => {
        console.log(result);
        res.status(201).json({
          message: "Done upload!"
        })
      })
    } catch (err) {
        console.log(err)
        res.status(500).send({
        error: 'An Error has occured trying to fetch'
    })}}
module.exports = (sequelize, DataTypes) => {
const Profile = sequelize.define('Profile', {
     files: {
      type: DataTypes.JSON
     },
     fullname: {
       type: DataTypes.STRING,
       allowNull: false
     },
     brandname: DataTypes.STRING,
     skill1: DataTypes.STRING,
     skill2: DataTypes.STRING,
     skill3: DataTypes.STRING,
     skill4: DataTypes.STRING,
     socail_handle1: DataTypes.STRING,
     socail_handle2: DataTypes.STRING
 })
 return Profile 
 }
const AuthController = require('./controllers/AuthController')
const AuthControllerPolicy = require('./policies/AuthControllerPolicy')
const ProfileControler = require('./controllers/ProfileController')
const upload = require ('multer')

module.exports = (app) => {
app.post('/register',
    AuthControllerPolicy.register,
    AuthController.register)

app.post('/login',
    AuthController.login)

app.get('/profile',
    ProfileControler.index)
    
app.post('/upload', upload.single('file'),
    ProfileControler.upload)
}我注意到两件事:

  • 您没有将multer用作中间件功能
  • upload.single('file')
    返回一个函数,该函数应在Express routes中作为中间件传递。您可以在
    route.js中这样使用它:

    const multer=require('multer');
    const upload=multer({
    目标:“../public”,
    文件过滤器,
    });
    app.post('/upload',upload.single('file'),ProfileController.post);
    
    然后,您可以在post功能中删除上载代码:

    module.exports.post=async(req,res)=>{
    //Multer使您的文件在req.file中可用
    const file=req.file;
    试一试{
    //创建新的Mongo对象时无需等待
    常量配置文件=新配置文件({
    profile:this.profile,
    档案:档案
    });
    //将其重构为使用async/await而不是Promissions。
    //避免将承诺与异步/等待混合。
    const result=wait profile.save();
    返回res.status(201.json)({message:“Done upload!”});
    }捕获(错误){
    console.log(错误)
    返回res.status(500).send({error:'尝试获取'}时发生错误);
    }
    }
    
  • 传递给multer的文件输入的名称与前端不匹配
  • 您正在配置multer以查找名为
    files
    upload.single('files')
    ,但在前端您将其命名为
    file
    (单数):
    formData.append('file',this.files)
    。通常情况下,穆特会扔一个球。确保这两个完全匹配


    此免费指南将帮助您处理Node.js中的文件上载。

    可能是签出-我知道这不是一个正确的答案,这取决于您的要求是创建自己的上载程序,还是只希望在Vue中简单地上载文件。我与他们没有任何关系,这不是一个正确的答案,但我过去使用过Uppy,它似乎让这些事情变得更容易。我会检查一下,非常感谢……我会尝试一下。所以@maximOrlov,因为我已经在我的路线中添加了
    upload.single('file')
    。我的上传方法应该是什么样子
    upload.single('files')const profile=wait new profile({profile:this.profile,files:req.file
    Please!!!如果您发布路由文件(在其中导入`ProfileController.js`),我可以调整我的答案以适应您的问题。现在已添加路由文件…我已编辑我的答案以包括新的
    post
    方法。将路由器更改为使用
    ProfileController.post
    而不是
    ProfileController.upload
    ,因为您导出的方法名为
    post
    。我还重构了
    post方法一点,阅读注释。