【问题标题】:File upload using axios post with basic auth使用带有基本身份验证的 axios post 上传文件
【发布时间】:2019-06-07 14:33:20
【问题描述】:

我想使用 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】:

    您的数据已损坏

    传递 Axios 要么 普通对象或 FormData 对象。两者都可以。

    它不会正确序列化属性值之一是 FormData 对象的普通对象。

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

    您的内容类型已损坏

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

    您的服务器端代码可能不支持此功能

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

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 2013-06-27
      • 2017-10-19
      • 1970-01-01
      • 2017-06-18
      相关资源
      最近更新 更多