VueJS 上传带有附加数据的图片 [英] VueJS upload image with additional data

查看:16
本文介绍了VueJS 上传带有附加数据的图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像上传到服务器,同时使用以下方法传递一些额外的数据(在同一个 post 请求中):VueJS 2 (CLI 3)、axios、multer、sharp,我有 NodeJS后端的 MongoDB.

前端:

<div class="输入"><label for="name">名称:</label><输入类型=文本"id="姓名"v-model="名称">

<div class="输入"><label for="last_name">您的姓氏:</label><输入类型=文本"id="姓氏"v-model="last_name">

<div class="输入"><label for="permalink">permalink</label><输入类型=文本"id="永久链接"v-model="永久链接">

<div class="输入"><label for="price">price</label><输入类型=文本"id="价格"v-model="价格">

<div class="输入"><label for="photo">photo</label><输入风格=显示:无"类型=文件"身份证=照片"@change="onFileSelected"ref="文件输入"><div @click="$refs.fileInput.click()">选择文件</div>

<div class="提交"><md-button type="submit" class="md-primary md-raised">提交</md-button>

</表单>

VueJS 方法:

从 'axios' 导入 axios导出默认{数据 () {返回 {名称: '',姓: '',固定链接:'',选定文件:空,网址:空,价格:0,第二个:假的}},方法: {onFileSelected(事件){this.selectedFile = event.target.files[0]this.url = URL.createObjectURL(this.selectedFile)},上传(){const fd = new FormData()fd.append('image', this.selectedFile, this.selectedFile.name)axios.post('http...', fd, {onUploadProgress:uploadEvent =>{console.log('上传进度' + Math.round(uploadEvent.loaded/uploadEvent.total * 100) + '%')}}).then(res => {控制台日志(res)})},提交(){const fd = new FormData()fd.append('image', this.selectedFile, this.selectedFile.name)fd.append('data', this.name, this.last_name)axios.post('http://localhost:7000/api/create-user', fd, {onUploadProgress:uploadEvent =>{console.log('上传进度' + Math.round(uploadEvent.loaded/uploadEvent.total * 100) + '%')}}).then(res => {控制台日志(res)如果(res.data === 'ok'){this.second = 真}}).然后(设置超时(函数(){this.second = falsethis.reset()}.bind(this), 2000)).catch(error => console.log(error))}}}

NodeJS:

controller.postCreateUser = (req, res) =>{constSharp = require('sharp');const fs = require('fs');const folderImg = '后端/上传/';console.log(JSON.stringify(req.body));控制台日志(请求文件);res.send("ok");};

req.file 的结果是(这很好):

{ fieldname: 'image',originalname: 'musk.jpg',编码:'7bit',mimetype: '图像/jpeg',目的地:'后端/上传/原始​​/',文件名:'musk-1545470459038.jpg',路径:'backend\uploads\original\musk-1545470459038.jpg',大小:108787 }

console.log(req.body)的结果是

{"data":""}

问题是这里数据有空字符串,我没有收到任何数据.我需要将数据存储到我的数据库中.怎么做?

如果有什么对你来说不是很清楚,请向我询问更多细节.

解决方案

在你的 onSubmit 方法中,你这样做:

const fd = new FormData()fd.append('image', this.selectedFile, this.selectedFile.name)fd.append('data', this.name, this.last_name)

但是 FormData.append() 期望这些参数:

第三个参数不适用于这一行:fd.append('data', this.name, this.last_name)

相反,您可以执行以下任一操作:

fd.append('data', `${this.name} ${this.last_name}`)//发送单个字符串

//分别发送两个字符串fd.append('name', this.name)fd.append('last_name', this.last_name)

//将数据作为 JSON 发送fd.append('data', JSON.stringify({name: this.name, last_name: this.last_name}))

I am trying to upload image to the server and the same time to pass some additional data (in the same post request) using: VueJS 2 (CLI 3), axios, multer, sharp and I have NodeJS with MongoDB in the backend.

Front-end:

<form @submit.prevent="onSubmit" enctype="multipart/form-data">
   <div class="input">
      <label for="name">Name: </label>
        <input
          type="text"
          id="name"
          v-model="name">
    </div>
    <div class="input">
        <label for="last_name">Your last_name: </label>
        <input
              type="text"
              id="last_name"
              v-model="last_name">
     </div>
     <div class="input">
        <label for="permalink">permalink</label>
        <input
              type="text"
              id="permalink"
               v-model="permalink">
     </div>
     <div class="input">
       <label for="price">price</label>
       <input
             type="text"
             id="price"
             v-model="price">
      </div>
      <div class="input">
        <label for="photo">photo</label>
        <input
          style="display: none"
          type="file"
          id="photo"
          @change="onFileSelected"
          ref="fileInput">
        <div @click="$refs.fileInput.click()">Pick file</div>
        </div>
        <div class="submit">
          <md-button type="submit" class="md-primary md-raised">Submit</md-button>
        </div>
</form>

VueJS methods:

import axios from 'axios'
export default {
  data () {
    return {
      name: '',
      last_name: '',
      permalink: '',
      selectedFile: null,
      url: null,
      price: 0,
      second: false
    }
  },
  methods: {
    onFileSelected (event) {
      this.selectedFile = event.target.files[0]
      this.url = URL.createObjectURL(this.selectedFile)
    },
    onUpload () {
      const fd = new FormData()
      fd.append('image', this.selectedFile, this.selectedFile.name)
      axios.post('http...', fd, {
        onUploadProgress: uploadEvent => {
          console.log('Upload Progress ' + Math.round(uploadEvent.loaded / uploadEvent.total * 100) + ' %')
        }
      })
        .then(res => {
          console.log(res)
        })
    },
    onSubmit () {
      const fd = new FormData()          
      fd.append('image', this.selectedFile, this.selectedFile.name)
      fd.append('data', this.name, this.last_name)

      axios.post('http://localhost:7000/api/create-user', fd, {
        onUploadProgress: uploadEvent => {
          console.log('Upload Progress ' + Math.round(uploadEvent.loaded / uploadEvent.total * 100) + ' %')
        }
      })
        .then(res => {
          console.log(res)
          if (res.data === 'ok') {
            this.second = true
          }
        })
        .then(
          setTimeout(function () {
            this.second = false
            this.reset()
          }.bind(this), 2000)
        )
        .catch(error => console.log(error))
    }
  }
}

NodeJS:

controller.postCreateUser = (req, res) => {
  const sharp = require('sharp');
  const fs = require('fs');
  const folderImg = 'backend/uploads/';
  console.log(JSON.stringify(req.body));
  console.log(req.file);
  res.send("ok");    
};

The results of req.file is (which is good):

{ fieldname: 'image',
  originalname: 'musk.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: 'backend/uploads/original/',
  filename: 'musk-1545470459038.jpg',
  path: 'backend\uploads\original\musk-1545470459038.jpg',
  size: 108787 }

The results of console.log(req.body) is

{"data":""}

The problem is here data has empty string and I don't receive any data. I need having the data to store to my database. How to do that?

If something isn't very clear to you, ask me for more details.

解决方案

In your onSubmit method, you do this:

const fd = new FormData()
fd.append('image', this.selectedFile, this.selectedFile.name)
fd.append('data', this.name, this.last_name)

But FormData.append() expects these parameters:

The third parameter does not apply on this line: fd.append('data', this.name, this.last_name)

Instead, you can do either of these:

fd.append('data', `${this.name} ${this.last_name}`) // Send a single String

or

// Send both Strings separately
fd.append('name', this.name)
fd.append('last_name', this.last_name)

or

// Send the data as JSON
fd.append('data', JSON.stringify({name: this.name, last_name: this.last_name}))

这篇关于VueJS 上传带有附加数据的图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆