【问题标题】:VueJS upload image with additional dataVueJS 上传带有附加数据的图像
【发布时间】:2018-12-22 10:01:26
【问题描述】:

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

前端:

<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 方法:

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");    
};

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

{ 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 }

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

{"data":""}

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

如果您对某些事情不是很清楚,请向我询问更多详细信息。

【问题讨论】:

  • 我认为你的问题出在这条线上,在前端:fd.append('data', this.name, this.last_name)。您正在传递 3 个参数,而在发送字符串时只允许 2 个。您只能使用 3 个when sending a file。您可以连接两个字符串:this.name + ' ' + this.last_name,或分别发送两个属性:fd.append('name', this.name); fd.append('last_name', this.last_name); ,或以 JSON 格式发送数据
  • 这就是问题所在,如果您想使用 JSON 等替代答案,您可以将其添加为解决方案
  • 很高兴它成功了!

标签: vue.js vuejs2 axios


【解决方案1】:

在您的 onSubmit 方法中,您可以这样做:

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

但是FormData.append() 需要这些参数:

  • name - value 中包含其数据的字段的名称。
  • value - 字段的值。这可以是 USVString 或 Blob(包括 File 等子类)。
  • filename 可选 - 报告给服务器的文件名(USVString),当 Blob 或 File 作为第二个参数传递时。

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2011-07-28
    • 2012-09-21
    • 2014-02-03
    • 2016-06-17
    • 1970-01-01
    相关资源
    最近更新 更多