文件上传提交时为空

我正在尝试使用对象内的 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>

  );

}


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


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

http://img1.mukewang.com/649d98e10001ccb409430363.jpg

宝慕林4294392
浏览 173回答 2
2回答

幕布斯7119047

通过将文件转换为 base64 字符串解决了这个问题。function getBase64(file) {&nbsp; return new Promise(function(resolve, reject) {&nbsp; &nbsp; const reader = new FileReader();&nbsp; &nbsp; reader.onload = function() {&nbsp; &nbsp; &nbsp; resolve(reader.result);&nbsp; &nbsp; };&nbsp; &nbsp; reader.onerror = reject;&nbsp; &nbsp; reader.readAsDataURL(file);&nbsp; });}const [form, setForm] = useState([]);const fileFound = e.target.type === 'file' && e.target.files[0];const promise = fileFound && getBase64(fileFound);promise.then(function(result) {&nbsp; &nbsp;setForm([&nbsp; &nbsp; &nbsp; ...form,&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;UUID_Answer: 'image_name,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Answer: '',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Document: true,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Document_Upload: result,&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp;]);});const submitData = {&nbsp; &nbsp; UUID_Formulier: '117F994F-F803-7249-91E9-EE1E7B691DFF',&nbsp; &nbsp; answers: form,&nbsp; };axios&nbsp; .post('/submit', submitData)&nbsp; .then(() => {&nbsp; &nbsp; console.log('success');&nbsp; })&nbsp; .catch(() => {&nbsp; &nbsp; console.log('failed error');&nbsp; });

斯蒂芬大帝

所有数据都必须添加到 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');&nbsp;console.log(formData) // I get formData dataaxios&nbsp; .post('/submit', formData, {&nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; 'Content-Type': 'multipart/form-data',&nbsp; &nbsp; },&nbsp; })&nbsp; .then(() => {&nbsp; &nbsp; console.log('success');&nbsp; })&nbsp; .catch(() => {&nbsp; &nbsp; console.log('failed error');&nbsp; });};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript