VueJS上载带有其他数据的图像 [英] VueJS upload image with additional data

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

问题描述

我正在尝试使用以下命令将图像上传到服务器,并同时传递一些附加数据(在同一发布请求中): VueJS 2(CLI 3),axios,multer,sharp,并且我有NodeJS与后端是MongoDB.

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.

前端:

<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的结果是(很好):

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 }

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

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.

推荐答案

在您的onSubmit方法中,您可以执行以下操作:

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)

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

  • name-其数据包含在value中的字段的名称.
  • value-字段的值.这可以是USVString或Blob(包括子类,例如File).
  • filename 可选-当将Blob或文件作为第二个参数传递时,报告给服务器的文件名(USVString).
  • name - The name of the field whose data is contained in value.
  • value - The field's value. This can be a USVString or Blob (including subclasses such as File).
  • filename Optional - The filename reported to the server (a USVString), when a Blob or File is passed as the second parameter.

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

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

// 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}))

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆