Javascript 使用Axios Post方法上传Csv文件内容?

Javascript 使用Axios Post方法上传Csv文件内容?,javascript,reactjs,csv,papaparse,csvreader,Javascript,Reactjs,Csv,Papaparse,Csvreader,我正在尝试上载csv文件内容我有一个api,它可以通过…AZ使用表单读取csv文件头,但我需要上载csv文件内容而不是csv文件我正在尝试上载,但失败了我尝试了csv.parse和papa parse,这是我迄今为止尝试的代码。请帮助我错误在哪里。请帮助我只能上传csv格式的文件内容,而不能上传文件详细信息 import React, { Component } from "react"; // import { CsvToHtmlTable } from "react-csv-to-table

我正在尝试上载csv文件内容我有一个api,它可以通过…AZ使用表单读取csv文件头,但我需要上载csv文件内容而不是csv文件我正在尝试上载,但失败了我尝试了csv.parse和papa parse,这是我迄今为止尝试的代码。请帮助我错误在哪里。请帮助我只能上传csv格式的文件内容,而不能上传文件详细信息

import React, { Component } from "react";
// import { CsvToHtmlTable } from "react-csv-to-table";
import ReactFileReader from "react-file-reader";
import { withTranslation } from "react-i18next";
import config from "../Main";
import axios from "axios";
import Swal from "sweetalert2";
import cross from "../../img/Cross.png";
import Papa from "papaparse";
import csv from "csv";
import { CSVReader } from "react-papaparse";

let authToken = localStorage.getItem("Token");

class Import extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cost_type: null,
      invoice_number: "",
      csv: ", // this is where i need to upload csv file content
      mapping: {
        date: "",
        car: "",
        car_vin: "",
        car_plate_number: "",
        car_mileage: "",
        value: "",
        invoice_number: "",
        cost_type: "",
        description: "",
        net_value: "",
        quantity: ""
      },
      start_row: null,
      label: []
    };
    this.fileInput = React.createRef();
    this.onChange = this.onChange.bind(this);

  }


  handleImportOffer = () => {
    this.fileInput.current.click();
  };

  async handleChange1(event) {
    const { name, value } = event.target;
    await this.setState({
      mapping: {
        ...this.state.mapping,
        [name]: value.toUpperCase()
      }
    });
    console.log(this.state.mapping);
  }

  async onChange(event) {
    await this.setState({
      [event.target.name]: event.target.value
    });
    }
  }
 onChange1(e) {
    this.setState({ csv: e.target.files[0] });
    console.log("Csv File", this.state.csv);
  }
  handleSubmit(e) {
    e.preventDefault();
    let authToken = localStorage.getItem("Token");


    // Here i was trying to read file content and upload it
    const reader = new FileReader();
    reader.onload = () => {
      csv.parse(reader.result, (err, data) => {
        var userList = [];
        const csv = data;
        const newUser = {
          csv: csv
        };
        userList.push(newUser);
      });
    };

    const data = {
      cost_type: this.state.cost_type,
      invoice_number: this.state.invoice_number,
      csv: this.state.csv, //and in this i wanted to upload content of the file 
      mapping: { ...this.state.mapping },
      start_row: this.state.start_row
    };



    axios({
      method: "post",
      url: `https://digitalfleet.eu/api/1/costs/upload/`,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        // 'Content-Type': 'multipart/form-data'
        Authorization: "Bearer " + JSON.parse(authToken)
      },
      data
    })
      .then(res => {
        this.setState({
          cost_type: null,
          invoice_number: "",
          csv: "",
          mapping: {
            date: "",
            car: "",
            car_vin: "",
            car_plate_number: "",
            car_mileage: "",
            value: "",
            invoice_number: "",
            cost_type: "",
            description: "",
            net_value: "",
            quantity: ""
          },
          start_row: null
        });

        Swal.fire({
          title: "Cost Added",
          type: "success",
          text: "Cost Added Successfully on database !",
          showConfirmButton: false,
          timer: 2000
        });

      })
      .catch(err => {
        console.log(err);
        Swal.fire({
          title: "Cost Added",
          type: "error",
          text:
            "Error While adding cost please check type correct input value !!",
          timer: 3000
        });

      });
  }

  handleChange = event => {
    // const reader = new FileReader();
    this.setState({
      csv: event.target.files[0]
    });
    // reader.readAsBinaryString(csv);
    console.log(event.target.files[0]);
  };





  render() {

    const { t } = this.props;
    const {
      label

    } = this.state;

    return (
      <div>
        <div id="invoice" className="modal">
          <a
            href="# "
            rel="modal:close"
            className="float-right text-white h4"
            style={{ marginBottom: "90px" }}
          >
            <img src={cross} alt="Cross" style={{ height: "0.7em" }} />
          </a>
          <p className="mod" style={{ marginTop: "40px" }}>
            {t("importInvoice")}
          </p>
          <hr></hr>
          <form
            noValidate
            autoComplete="off"
            onSubmit={this.handleSubmit}
            style={{}}
          >
            <div classNam="import_invoice">
              <div className="form-group" style={{ marginTop: "15px" }}>
                <label for="exampleInputEmail1" id="ppp">
                  {t("cost_type").toUpperCase()}
                </label>
                <select
                  name="cost_type"
                  value={this.state.cost_type}
                  onChange={this.onChange}
                  class="form-control donn"
                  style={{ width: "300px", marginTop: "10px" }}
                >
                  <option value="" disabled selected hidden>
                    {t("choose")}
                  </option>
                  {label.map((c, i) => (
                    <option value={c.value} key={i}>
                      {c.display_name}
                    </option>
                  ))}
                </select>
              </div>

              <div className="row">
                <div className="col-md-4">
                  <div className="form-group" style={{ marginTop: "35px" }}>
                    <p id="ppp">{t("import_cost_file")}</p>
                    {/* <p id="pp">{t("file_size")}</p> */}

                    {/* <ReactFileReader
                      multipleFiles={false}
                      fileTypes={[".csv"]}
                      handleFiles={this.handleFiles}
                    >
                      <button className="btn" id="bttn">
                        {t("import_cost_file").toUpperCase()}
                        <span className="float-right">
                          <i class="fa fa-paperclip"></i>
                        </span>
                      </button>
                    </ReactFileReader> */}

                    <div class="upload-btn-wrapper">
                      <button class="btn112" style={{ fontSize: "16px" }}>
                        {t("select_file").toUpperCase()}
                      </button>
                      <input
                        type="file"
                        name="csv"
                        //value={this.state.csv}
                        onChange={this.handleChange}

                        //onChange={this.onChange}
                      />
                    </div>
                  </div>
                </div>

                <div className="col-md-4" style={{ marginTop: "65px" }}>
                  <label
                    for="exampleInputEmail1"
                    className="font-weight-bold h6"
                    style={{ fontSize: "13px" }}
                  >
                    {t("import_data_from_row").toUpperCase()}
                  </label>
                  <input
                    style={{ marginTop: "6px" }}
                    type="number"
                    min={1}
                    value={this.state.start_row}
                    onChange={this.onChange}
                    placeholder={t("type")}
                    name="start_row"
                  />
                </div>

                {this.state.cost_type === "fuel-card" && (
                  <div className="col-sm-4" style={{ marginTop: "65px" }}>
                    <label
                      for="exampleInputEmail1"
                      className="font-weight-bold h6"
                      style={{ fontSize: "13px" }}
                    >
                      {t("invoice_number").toUpperCase()}
                    </label>
                    <input
                      type="text"
                      placeholder={t("type")}
                      name="invoice_number"
                      value={this.state.invoice_number}
                      className="form-control"
                      onChange={this.onChange}
                    />
                  </div>
                )}
              </div>

              <p className=" " id="ppp">
                {t("select_columns").toUpperCase()}
              </p>
              <div className="row" style={{ marginTop: "25px" }}>
                <div className="col-sm-3">
                  <label
                    for="exampleInputEmail1"
                    className="font-weight-bold h6"
                    style={{ fontSize: "13px" }}
                  >
                    {t("date").toUpperCase()}
                  </label>
                  <input
                    type="text"
                    placeholder={t("type")}
                    maxLength={2}
                    className="form-control"
                    name="date"
                    value={this.state.mapping.date}
                    // value={
                    //   this.state.invoice_type === "fuel-card"
                    //     ? `${date1}`
                    //     : `${this.state.date}`
                    // }

                    onChange={this.handleChange1.bind(this)}
                    class="form-control donn"
                  />
                </div>

                <div className="col-sm-4">
                  <label
                    for="exampleInputEmail1"
                    className="font-weight-bold h6"
                    style={{ fontSize: "13px" }}
                  >
                    {t("plate_number").toUpperCase()}
                  </label>
                  <input
                    type="text"
                    placeholder={t("type")}
                    maxLength={2}
                    className="form-control"
                    name="car_plate_number"
                    value={this.state.mapping.car_plate_number}
                    // value={
                    //   this.state.invoice_type === "fuel-card"
                    //     ? `${plate_number1}`
                    //     : `${this.state.plate_number}`
                    // }
                    // value={this.state.plate_number}
                    onChange={this.handleChange1.bind(this)}
                  />
                </div>

                <div className="col-sm-2">
                  <label
                    for="exampleInputEmail1"
                    className="font-weight-bold h6"
                    style={{ fontSize: "13px" }}
                  >
                    {t("vin").toUpperCase()}
                  </label>
                  <input
                    type="text"
                    placeholder={t("type")}
                    maxLength={2}
                    className="form-control"
                    name="car_vin"
                    value={this.state.mapping.car_vin}
                    onChange={this.handleChange1.bind(this)}
                  />
                </div>

                {this.state.cost_type === "fuel-card" ? (
                  <p></p>
                ) : (
                  <div className="col-sm-3">
                    <label
                      for="exampleInputEmail1"
                      className="font-weight-bold h6"
                      style={{ fontSize: "13px" }}
                    >
                      {t("invoice_number").toUpperCase()}
                    </label>
                    <input
                      type="text"
                      placeholder={t("type")}
                      maxLength={2}
                      className="form-control"
                      name="invoice_number"
                      value={this.state.mapping.invoice_number}
                      onChange={this.handleChange1.bind(this)}
                    />
                  </div>
                )}
              </div>

              <div className="row" style={{ marginTop: "25px" }}>
                <div className="col-sm-3">
                  <label
                    for="exampleInputEmail1"
                    className="font-weight-bold h6"
                    style={{ fontSize: "13px" }}
                  >
                    {t("description").toUpperCase()}
                  </label>
                  <input
                    type="text"
                    placeholder={t("type")}
                    maxLength={2}
                    className="form-control"
                    name="description"
                    value={this.state.mapping.description}
                    onChange={this.handleChange1.bind(this)}
                  />
                </div>
                <div className="col-sm-3">
                  <label
                    for="exampleInputEmail1"
                    className="font-weight-bold h6"
                    style={{ fontSize: "13px" }}
                  >
                    {t("quantity").toUpperCase()}
                  </label>
                  <input
                    type="text"
                    placeholder={t("type")}
                    maxLength={2}
                    className="form-control"
                    name="quantity"
                    value={this.state.mapping.quantity}
                    onChange={this.handleChange1.bind(this)}
                  />
                </div>

                <div className="col-sm-3">
                  <label
                    for="exampleInputEmail1"
                    className="font-weight-bold h6"
                    style={{ fontSize: "13px" }}
                  >
                    {t("price_netto_import").toUpperCase()}
                  </label>
                  <input
                    type="text"
                    placeholder={t("type")}
                    maxLength={2}
                    className="form-control"
                    name="net_value"
                    value={this.state.mapping.net_value}
                    onChange={this.handleChange1.bind(this)}
                  />
                </div>

                <div className="col-sm-3">
                  <label
                    for="exampleInputEmail1"
                    className="font-weight-bold h6"
                    style={{ fontSize: "13px" }}
                  >
                    {t("price_brutto_import").toUpperCase()}
                  </label>
                  <input
                    type="text"
                    placeholder={t("type")}
                    maxLength={2}
                    className="form-control"
                    name="value"
                    value={this.state.mapping.value}
                    onChange={this.handleChange1.bind(this)}
                  />
                </div>
              </div>

              <div style={{ marginTop: "20px", marginBottom: "20px" }}>
                <center>
                  <button
                    type="submit"
                    value="Add Invoice"
                    style={{ background: "#b71c1c", color: "white" }}
                    className="btn btn-danger br"
                  >
                    {t("import_invoice")}
                  </button>
                </center>
              </div>
            </div>
          </form>


        </div>
      </div>
    );
  }
}

export default withTranslation()(Import);
import React,{Component}来自“React”;
//从“react csv to table”导入{CsvToHtmlTable};
从“react文件读取器”导入react文件读取器;
从“react-i18next”导入{withTranslation};
从“./Main”导入配置;
从“axios”导入axios;
从“sweetalert2”导入Swal;
从“../../img/cross.png”导入交叉;
从“papaparse”导入Papa;
从“csv”导入csv;
从“解析”导入{CSVReader};
让authToken=localStorage.getItem(“令牌”);
类导入扩展组件{
建造师(道具){
超级(道具);
此.state={
成本类型:空,
发票号:“”,
csv:“,//这是我需要上传csv文件内容的地方
映射:{
日期:“,
汽车:“,
车辆识别号:“,
汽车牌照号码:“”,
汽车行驶里程:“,
值:“”,
发票号:“”,
成本单位类型:“,
说明:“,
净值:“,
数量:“
},
起始行:空,
标签:[]
};
this.fileInput=React.createRef();
this.onChange=this.onChange.bind(this);
}
handleImportOffer=()=>{
this.fileInput.current.click();
};
异步handleChange1(事件){
常量{name,value}=event.target;
等待这一天({
映射:{
…此.state.mapping,
[名称]:value.toUpperCase()
}
});
log(this.state.mapping);
}
异步onChange(事件){
等待这一天({
[event.target.name]:event.target.value
});
}
}
更改1(e){
this.setState({csv:e.target.files[0]});
log(“Csv文件”,this.state.Csv);
}
handleSubmit(e){
e、 预防默认值();
让authToken=localStorage.getItem(“令牌”);
//在这里,我试图读取文件内容并上传它
const reader=new FileReader();
reader.onload=()=>{
csv.parse(reader.result,(err,data)=>{
var userList=[];
const csv=数据;
常量newUser={
csv:csv
};
push(newUser);
});
};
常数数据={
成本类型:this.state.cost类型,
发票编号:this.state.invoice\u编号,
csv:this.state.csv,//在这里我想上传文件的内容
映射:{…this.state.mapping},
开始行:this.state.start\u行
};
axios({
方法:“张贴”,
网址:`https://digitalfleet.eu/api/1/costs/upload/`,
标题:{
接受:“应用程序/json”,
“内容类型”:“应用程序/json”,
//“内容类型”:“多部分/表单数据”
授权:“承载者”+JSON.parse(authToken)
},
数据
})
。然后(res=>{
这是我的国家({
成本类型:空,
发票号:“”,
csv:“,
映射:{
日期:“,
汽车:“,
车辆识别号:“,
汽车牌照号码:“”,
汽车行驶里程:“,
值:“”,
发票号:“”,
成本单位类型:“,
说明:“,
净值:“,
数量:“
},
起始行:空
});
喷火({
标题:“增加成本”,
键入:“成功”,
文本:“在数据库上成功添加成本!”,
showconfixton:false,
计时器:2000
});
})
.catch(错误=>{
控制台日志(err);
喷火({
标题:“增加成本”,
键入:“错误”,
正文:
“添加成本时出错,请检查输入值是否正确!!”,
计时器:3000
});
});
}
handleChange=事件=>{
//const reader=new FileReader();
这是我的国家({
csv:event.target.files[0]
});
//reader.readAsBinaryString(csv);
console.log(event.target.files[0]);
};
render(){
const{t}=this.props;
常数{
标签
}=本州;
返回(

{t(“importInvoice”)}


{t(“cost_type”).toUpperCase()} {t(“选择”)} {label.map((c,i)=>( {c.display_name} ))}

{t(“导入成本文件”)}

{/*

{t(“文件大小”)}

*/} {/* {t(“导入成本文件”).toUpperCase()} */} {t(“选择文件”).toUpperCase()} {t(“从_行导入_数据”).toUpperCase()} {this.state.cost_type===“燃料卡”&&( {t(“发票号码”).toUpperCase()} )}

{t(“选择列”).t