reactjs React.js,如何将多部分/表单数据发送到服务器

ifmq2ha2  于 2023-03-08  发布在  React
关注(0)|答案(8)|浏览(181)

我们想发送一个图像文件作为multipart/表单到后端,我们尝试使用html表单来获取文件并发送文件作为formData,下面是代码

export default class Task extends React.Component {

  uploadAction() {
    var data = new FormData();
    var imagedata = document.querySelector('input[type="file"]').files[0];
    data.append("data", imagedata);

    fetch("http://localhost:8910/taskCreationController/createStoryTask", {
      mode: 'no-cors',
      method: "POST",
      headers: {
        "Content-Type": "multipart/form-data"
        "Accept": "application/json",
        "type": "formData"
      },
      body: data
    }).then(function (res) {
      if (res.ok) {
        alert("Perfect! ");
      } else if (res.status == 401) {
        alert("Oops! ");
      }
    }, function (e) {
      alert("Error submitting form!");
    });
  }

  render() {
    return (
        <form encType="multipart/form-data" action="">
          <input type="file" name="fileName" defaultValue="fileName"></input>
          <input type="button" value="upload" onClick={this.uploadAction.bind(this)}></input>
        </form>
    )
  }
}

后端错误为 “嵌套异常为org.springframework.web.multipart.MultipartException:无法分析多部分servlet请求;嵌套异常是java.io.IOException:org.apache.tomcat.util.http.fileupload.FileUploadException:请求被拒绝,因为找不到多部分边界”.
阅读了这个之后,我们试着在fetch中给头文件设置边界:

fetch("http://localhost:8910/taskCreationController/createStoryTask", {
      mode: 'no-cors',
      method: "POST",
      headers: {
        "Content-Type": "multipart/form-data; boundary=AaB03x" +
        "--AaB03x" +
        "Content-Disposition: file" +
        "Content-Type: png" +
        "Content-Transfer-Encoding: binary" +
        "...data... " +
        "--AaB03x--",
        "Accept": "application/json",
        "type": "formData"
      },
      body: data
    }).then(function (res) {
      if (res.ok) {
        alert("Perfect! ");
      } else if (res.status == 401) {
        alert("Oops! ");
      }
    }, function (e) {
      alert("Error submitting form!");
    });
  }

这一次,后端的错误是:* 路径为[]的上下文中的servlet [dispatcherServlet]的Servlet.service()引发异常[请求处理失败;嵌套异常为java.lang.NullPointerException],其根本原因为 *
我们添加多部分边界正确吗?它应该在哪里?也许我们一开始是错的,因为我们没有得到多部分/表单数据。我们如何才能得到正确的呢?

tuwxkamq

tuwxkamq1#

我们只是尝试删除我们的标题和它的工作!

fetch("http://localhost:8910/taskCreationController/createStoryTask", {
      mode: 'no-cors',
      method: "POST",
      body: data
    }).then(function (res) {
      if (res.ok) {
        alert("Perfect! ");
      } else if (res.status == 401) {
        alert("Oops! ");
      }
    }, function (e) {
      alert("Error submitting form!");
    });
hgb9j2n6

hgb9j2n62#

下面是我通过axios上传预览图像的解决方案。

import React, { Component } from 'react';
import axios from "axios";

React组件类:

class FileUpload extends Component {

    // API Endpoints
    custom_file_upload_url = `YOUR_API_ENDPOINT_SHOULD_GOES_HERE`;

    constructor(props) {
        super(props);
        this.state = {
            image_file: null,
            image_preview: '',
        }
    }

    // Image Preview Handler
    handleImagePreview = (e) => {
        let image_as_base64 = URL.createObjectURL(e.target.files[0])
        let image_as_files = e.target.files[0];

        this.setState({
            image_preview: image_as_base64,
            image_file: image_as_files,
        })
    }

    // Image/File Submit Handler
    handleSubmitFile = () => {

        if (this.state.image_file !== null){

            let formData = new FormData();
            formData.append('customFile', this.state.image_file);
            // the image field name should be similar to your api endpoint field name
            // in my case here the field name is customFile

            axios.post(
                this.custom_file_upload_url,
                formData,
                {
                    headers: {
                        "Authorization": "YOUR_API_AUTHORIZATION_KEY_SHOULD_GOES_HERE_IF_HAVE",
                        "Content-type": "multipart/form-data",
                    },                    
                }
            )
            .then(res => {
                console.log(`Success` + res.data);
            })
            .catch(err => {
                console.log(err);
            })
        }
    }

    // render from here
    render() { 
        return (
            <div>
                {/* image preview */}
                <img src={this.state.image_preview} alt="image preview"/>

                {/* image input field */}
                <input
                    type="file"
                    onChange={this.handleImagePreview}
                />
                <label>Upload file</label>
                <input type="submit" onClick={this.handleSubmitFile} value="Submit"/>
            </div>
        );
    }
}

export default FileUpload;
l7mqbcuq

l7mqbcuq3#

该文件也可在以下事件中使用:

e.target.files[0]

(无需document.querySelector('input[type="file"]').files[0];

uploadAction(e) {
  const data = new FormData();
  const imagedata = e.target.files[0];
  data.append('inputname', imagedata);
  ...

**注意:**使用console.log(data.get('inputname'))进行调试,console.log(data)不会显示追加的数据。

busg9geu

busg9geu4#

https://muffinman.io/uploading-files-using-fetch-multipart-form-data/最适合我,它使用formData。

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import Button from "react-bootstrap/Button";

const ReactDOM = require("react-dom");

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.test = this.test.bind(this);
    this.state = {
      fileUploadOngoing: false
    };
  }

  test() {
    console.log(
      "Test this.state.fileUploadOngoing=" + this.state.fileUploadOngoing
    );
    this.setState({
      fileUploadOngoing: true
    });

    const fileInput = document.querySelector("#fileInput");
    const formData = new FormData();

    formData.append("file", fileInput.files[0]);
    formData.append("test", "StringValueTest");

    const options = {
      method: "POST",
      body: formData
      // If you add this, upload won't work
      // headers: {
      //   'Content-Type': 'multipart/form-data',
      // }
    };
    fetch("http://localhost:5000/ui/upload/file", options);
  }
  render() {
    console.log("this.state.fileUploadOngoing=" + this.state.fileUploadOngoing);
    return (
      <div>
        <input id="fileInput" type="file" name="file" />
        <Button onClick={this.test} variant="primary">
          Primary
        </Button>

        {this.state.fileUploadOngoing && (
          <div>
            <h1> File upload ongoing abc 123</h1>
            {console.log(
              "Why is it printing this.state.fileUploadOngoing=" +
                this.state.fileUploadOngoing
            )}
          </div>
        )}

      </div>
    );
  }
}
mpgws1up

mpgws1up5#

React文件上载组件

import { Component } from 'react';

class Upload extends Component {
  constructor() {
    super();
    this.state = {
      image: '',
    }
  }

  handleFileChange = e => {
    this.setState({
      [e.target.name]: e.target.files[0],
    })
  }

  handleSubmit = async e => {
    e.preventDefault();

    const formData = new FormData();
    for (let name in this.state) {
      formData.append(name, this.state[name]);
    }

    await fetch('/api/upload', {
      method: 'POST',
      body: formData,
    });

    alert('done');
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input 
          name="image" 
          type="file"
          onChange={this.handleFileChange}>
        </input>
        <input type="submit"></input>
      </form>
    )
  }
}

export default Upload;
bkhjykvo

bkhjykvo6#

请求被拒绝,因为找不到多部分边界”。
当你发送multipart/form-data时,边界会自动添加到请求头的content-type中。当参数以边界规则结束时,你必须告诉服务器。你必须这样设置Content-type

"Content-Type": `multipart/form-data: boundary=add-random-characters`

本文将指导您:https://roytuts.com/boundary-in-multipart-form-data/
包含边界是为了分隔multipart/form-data中的名称/值对。boundary参数的作用类似于multipart/form-data中每对名称和值的标记。boundary参数自动添加到http(超文本传输协议)请求标头的Content-Type中。

f4t66c6m

f4t66c6m7#

我正在使用云计算,无法推送与上述相同的视频问题,在下面添加了代码以了解详细信息,它对我来说运行良好。files[0]是用于存储文件并将数据作为数组追加的useState

var formData = new FormData()
formData.append('files', files[0])
for (var [key, value] of formData.entries()) {
  console.log(key, value)
}
fetch('url', {
  method: 'POST',
  body: formData,
  redirect: 'follow',
})
.then(res => console.log(res))

这解决了我的问题,只是添加重定向。希望这可能会有帮助。

wi3ka0sx

wi3ka0sx8#

发送multipart/formdata时,您需要避免使用contentType,因为浏览器会自动分配boundaryContent-Type
在您使用fetch的情况下,即使您避免使用Content-Type,它也会设置为默认的text/plain。因此,尝试使用jQuery ajax。如果我们将其设置为false,它会删除contentType
这是工作代码

var data = new FormData();
var imagedata = document.querySelector('input[type="file"]').files[0];
data.append("data", imagedata);
$.ajax({
    method: "POST",
    url: fullUrl,
    data: data,
    dataType: 'json',
    cache: false,
    processData: false,
    contentType: false
}).done((data) => {
    //resolve(data);
}).fail((err) => {
    //console.log("errorrr for file upload", err);
    //reject(err);
});

相关问题