Sending an axios Post request with csv in its body

走远了吗. 提交于 2021-02-10 17:44:08

问题


What i am trying to achieve is send a post request from my frontend to back end using axios.This post request has a csv file in its body.

Using postman : postman request

My code is this:

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

class SessionsUpdate extends Component {
  state = {
    selectedFile: null
  }


  handleSubmit = async () => {
    let formData = new FormData();
    formData.append('file', this.state.selectedFile);
    await axios.post(
      'https://localhost:8765/...', 
      formData,
      { headers: { 'x-observatory-auth': localStorage.getItem("token"), 'Content-Type': 'multipart/form-data' } }
    )

    console.log("log")  //this is not printed here
  }

  onFileChange = event => {
    this.setState({ selectedFile: event.target.files[0] });
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div>
          <h1>Choose a file to store</h1>
        </div>
        <div>
          <fieldset>
            <input type="file" accept=".csv" onChange={this.onFileChange} />
          </fieldset>
        </div>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default SessionsUpdate;

So the HTML part creates a simple GUI to select a csv file from local storage and what i want is to pass this csv file to my post request.After searching online the main way i found to do this is by using formdata but it does not work on my case and i have been stuck in this for quite a while.This requests works fine on postman though.

Any ideas about what i am missing?

来源:https://stackoverflow.com/questions/65674315/sending-an-axios-post-request-with-csv-in-its-body

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!