vue:V-input-file 不是“HTMLFormElement”类型的错误

问题描述

在 Vue 上将所选文件添加到 FormData 以 v-input-file 和 input type='file' 中的错误结束。

错误按摩: 无法构建“FormData”:参数 1 的类型不是“HTMLFormElement”。

<template>
 <Layout v-if="$store.state.user">

<v-form
      id='myform'
      name='myForm'
      class='myform'
      ref="form"
      lazy-validation
      enctype="multipart/form-data"
      method="POST"
    >
      <!-- FILE UP-LOAD -->
      <template>
        <v-file-input
          :rules="rules_fileInput"
          accept="image/png,image/jpeg,image/bmp"
          show-size
          counter
          label="PNG,JPEG,BMP"
          placeholder="Pick an image"
          prepend-icon="mdi-camera"
          @change="onFilePicked"
        />
      </template>

 <v-btn dark @click="submitForm">
      Save
 </v-btn>

 </v-form>
 </Layout>
 </template>

 <script>
   export default {
   data: () => ({
     imageUpload: null,}),methods: {
   onFilePicked(file) {
      this.imageUpload = file;
   },async submitForm() {
     
console.log('this.imageUpload:',this.imageUpload) // showing file 
//const headersImg = { headers:{ 'Content-Type':'multipart/form-data'}};


const { data } = await axios.post(
  url,new FormData(
    `files.${this.imageUpload.name}`,this.imageUpload,this.imageUpload.name
  )
);
 }

enter image description here

上图清楚一些文件数据。

如果我尝试像这样附加 FormData:

async submitForm() {

  const formData = new FormData();

  formData.append(
    `files.${this.imageUpload.name}`,this.imageUpload.name
  );

  //console.log('...formData:',...formData);
  const urlLocal = 'http://localhost:1337/upload';
  const urlLive = 'http://www.events-pr-server.ml/upload';

  // client in netlefy,server in heroku with: Allow all Origin - for this demo

  try {
    const { data } = await axios({
      method: 'post',url: urlLive,data: formData,headers: {
        'Content-Type': 'multipart/form-data',// 'Access-Control-Allow-Origin': '*',},});

结果为:文件为空

  1. tatusCode:400,错误:“错误的请求”,消息:“错误的请求”,...}。
  2. data: {errors: [{id: “Upload.status.empty”,message: “Files are 空”}]}。

enter image description here enter image description here

解决方法

根据您的最后一条评论,我创建了一个代码笔来检查问题。

  1. 我没有遇到 HTMLFormElement 错误,检查下面的代码笔 https://codepen.io/kurtesy_/pen/MWJBwQX?editors=1111

  2. 在 Post a formData using axios 旁边使用下面的协议,你需要指定 "Content-Type": "multipart/form-data"

    axios({
       method: "post",url: "your_url",data: formData,headers: { "Content-Type": "multipart/form-data" },})
       .then(function (response) {
         //handle success
         console.log(response);
       })
       .catch(function (response) {
         //handle error
         console.log(response);
       });
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...