【问题标题】:File Upload empty on submit提交时文件上传为空
【发布时间】:2021-02-14 09:44:35
【问题描述】:

我正在尝试在对象内使用 Axios 上传图像。我可以使用new FormData() 获取文件并将其放入对象中,但提交图像为空。如何结合其他 JSON 数据上传对象中的文件?

import React, { useState } from 'react';
import axios from 'axios';

function UploadFiles() {
  const [submitFile, setSubmitFile] = useState({});

  const handleChange = e => {
    setSubmitFile(e.target.files[0]);
  };

  const handleSubmit = () => {
    const formData = new FormData();
    formData.append('document', submitFile);
    formData.append('Answer_name', 'image');
    formData.append('Document', true);
    formData.append('Answer', 'Got some data');

    console.log(submitData) // I get formData data

    const submitData = {
      UUID_Formulier: '117F994F-F803-7249-91E9-EE1E7B691DFF',
      answers: [formData], // this will be an empty object on calling axios.post
    };
    axios
      .post('/submit', submitData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then(() => {
        console.log('success');
      })
      .catch(() => {
        console.log('failed error');
      });
  };

  return (
    <div>
      <input type="file" name="image" onChange={handleChange} />
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
}

图片必须放在 answers 数组中。当我将 FormData 放入 answers 数组时,它是一个空对象。如何将文件 formData 放入 JSON 对象或数组然后全部提交?

使用方括号表示法不会创建数组而是字符串,如下所示。

【问题讨论】:

    标签: javascript reactjs file-upload axios multipartform-data


    【解决方案1】:

    通过将文件转换为base64字符串来解决它。

    function getBase64(file) {
      return new Promise(function(resolve, reject) {
        const reader = new FileReader();
        reader.onload = function() {
          resolve(reader.result);
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });
    }
    
    const [form, setForm] = useState([]);
    const fileFound = e.target.type === 'file' && e.target.files[0];
    
    const promise = fileFound && getBase64(fileFound);
    
    promise.then(function(result) {
       setForm([
          ...form,
          {
             UUID_Answer: 'image_name,
             Answer: '',
             Document: true,
             Document_Upload: result,
          },
       ]);
    });
    
    const submitData = {
        UUID_Formulier: '117F994F-F803-7249-91E9-EE1E7B691DFF',
        answers: form,
      };
    
    axios
      .post('/submit', submitData)
      .then(() => {
        console.log('success');
      })
      .catch(() => {
        console.log('failed error');
      });
    

    【讨论】:

      【解决方案2】:

      您的所有数据都必须添加到 FormData 对象中,要以类似数组的形式获取数据,您可以尝试方括号表示法。

      const formData = new FormData();
      formData.append('UUID_Formulier', '117F994F-F803-7249-91E9-EE1E7B691DFF');
      formData.append('answers[0][document]', submitFile);
      formData.append('answers[0][Answer_name]', 'image');
      formData.append('answers[0][Document]', true);
      formData.append('answers[0][Answer]', 'Got some data'); 
      
      console.log(formData) // I get formData data
      
      axios
        .post('/submit', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
        .then(() => {
          console.log('success');
        })
        .catch(() => {
          console.log('failed error');
        });
      

      };

      【讨论】:

      • 感谢@Musa 的提示,不幸的是方括号表示法不会创建数组。检查更新的问题以获取发送到服务器的数据响应的屏幕截图。
      • 你在服务器端运行什么?
      • 服务端是laravel。
      • 使用 PHP,文件字段与文本字段是分开的,所以我认为您无法使用文件字段实现所需的结构
      猜你喜欢
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 2012-12-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 2014-11-16
      相关资源
      最近更新 更多