使用带有基本身份验证的axios帖子上传文件

问题描述 投票:-3回答:1

我想使用axios post请求将文件上传到服务器。

我正在使用输入标签进行文件和onChange设置状态。

如果我使用标题:{“content-type”:“multipart / form-data”},在axios中代码会给出错误400。

如果我删除它代码工作正常但通过POST发送空数组。

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

export default class Image extends Component {
  state = {
    image: null
  };

  handleFiles = e => {
    this.setState({ image: e.target.files[0] });
  };

  handleUpload = () => {
    var session_url = "https:/localhost:3000/wp-json/gf/v2/entries/";

    const fd = new FormData();
    fd.append("image", this.state.image);

    var entries = {
      form_id: "1",
      15: fd
    };

    axios
      .post(session_url, entries, {
        headers: { "content-type": "multipart/form-data" },

        withCredentials: true,
        auth: {
          username: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
          password: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        }
      })
      .then(res => {
        this.setState({ data: res.data });
        console.log(res, "Authenticated");
      })
      .catch(function(error) {
        console.log("Error on Authentication", error.message);
      });
  };
  render() {
    return (
      <div>
        <input type="file" onChange={this.handleFiles} />

        <button onClick={this.handleUpload}>Upload</button>
      </div>
    );
  }
}
javascript reactjs axios
1个回答
0
投票

Your data is broken

将Axios传递给普通对象或FormData对象。它可以处理两者。

它不能正确地序列化其中一个属性值是FormData对象的普通对象。

const entries = new FormData();
fd.append("image", this.state.image);
fd.append("form_id": "1");

Your content type is broken

不要手动设置Content-Type标头。它将从FormData对象生成(包括多部分请求的强制边界参数)。

Your server-side code might not support this

您需要确保服务器端代码可以处理多部分请求。

© www.soinside.com 2019 - 2024. All rights reserved.