reactjs FormData:数据不放置在formData中,并打印一个空对象

vi4fp9gy  于 2023-01-02  发布在  React
关注(0)|答案(2)|浏览(241)

我有一个项目要运行一个承包、建筑和施工公司,我必须创建发票,要创建发票,我必须向后端发送请求,请求的形式必须如下图所示:

界面应该是这样的:

问题是当我打印“formData”时它打印了一个空对象,即使我将数据传递给了“formData”,我如何解决这个问题呢?
这是空对象:

并且数据发送到后端时为空
当我打印时:

console.log(formData.get("invoice"));
    console.log(formData.get("data"));

控制台为:

null
[object Object]

file.js:

import React, { useState } from "react";
import InputAdornment from "@material-ui/core/InputAdornment";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";
import "date-fns";
import DateFnsUtils from "@date-io/date-fns";
// import {
//   KeyboardDatePicker,
//   MuiPickersUtilsProvider,
//   DatePicker,
// } from "@material-ui/pickers";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import CloudUploadIcon from "@material-ui/icons/CloudUpload";
import { addInvoice } from "../../../store/invoiceSlice";
import Icon from "@material-ui/core/Icon";
import { motion } from "framer-motion";
import { useDispatch } from "react-redux";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { alpha } from "@material-ui/core/styles";

const useStyles = makeStyles((theme) => ({
  root: {
    "& > *": {
      margin: theme.spacing(1),
    },
  },
  input: {
    display: "none",
  },
  button: {
    margin: theme.spacing(1),
    // padding: theme.spacing(4),
  },
}));

function ShippingTab(props) {
  const dispatch = useDispatch();
  const classes = useStyles();
  const [issueDate, setIssueDate] = useState(new Date());
  const [dueDate, setDueDate] = useState(new Date());
  const [netAmount, setNetAmount] = useState("");
  const [taxNumber, setTaxNumber] = useState("");
  const [grossAmount, setGrossAmount] = useState("");
  const [file, setFile] = useState(null);

  let formData = new FormData();
  const fileSelectedHandler = (event) => {
    console.log(event.target.files[0]);
    const file = event.target.files[0];

    if (event.target && file) {
      formData.append("invoice", file);
      setFile(file);
    }
  };
  const uploadHandler = (event) => {
    // fd.append("invoice", files);
    formData.append("data", {
      grossAmount,
      taxNumber,
      netAmount,
      dueDate,
      issueDate,
    });

    console.log("formmmmmmmmmmm Data: ", formData);
    // call api
    dispatch(addInvoice(formData));
  };

  const handleissueDateChange = (date) => {
    setIssueDate(date);
    console.log("date issssssssss: ", date);
    console.log("date issssssssss: ", issueDate);
  };

  const handleDueDateChange = (date) => {
    setDueDate(date);
  };

  const handleNetAmountChange = (event) => {
    setNetAmount(event.target.value);
  };

  const handleTaxAmountChange = (event) => {
    setTaxNumber(event.target.value);
  };

  const handleGrossAmountChange = (event) => {
    setGrossAmount(event.target.value);
  };
  return (
    <>
      {/* <MuiPickersUtilsProvider utils={DateFnsUtils}>
        <div className="flex -mx-4">
          <KeyboardDatePicker
            inputVariant="outlined"
            className="mt-8 mb-16"
            margin="normal"
            id="date-picker-dialog"
            label="issue Date"
            format="MM/dd/yyyy"
            KeyboardButtonProps={{
              "aria-label": "change date",
            }}
            value={issueDate}
            onChange={handleissueDateChange}
          /> */}

      <div className="flex -mx-4">
        <TextField
          id="date"
          variant="outlined"
          label="Choose Issue Date"
          className="mt-8 mb-16 mr-5"
          type="date"
          defaultValue={issueDate}
          InputLabelProps={{
            shrink: true,
          }}
          // value={issueDate}
          onChange={handleissueDateChange}
          fullWidth
        />

        <TextField
          id="date"
          variant="outlined"
          className="mt-8 mb-16"
          label="Choose Due Date"
          type="date"
          defaultValue={dueDate}
          InputLabelProps={{
            shrink: true,
          }}
          // value={dueDate}
          onChange={handleDueDateChange}
          fullWidth
        />
      </div>
      {/* <KeyboardDatePicker
            inputVariant="outlined"
            className="mt-8 mb-16 ml-6"
            margin="normal"
            id="date-picker-dialog"
            label="Due Date"
            format="MM/dd/yyyy"
            KeyboardButtonProps={{
              "aria-label": "change date",
            }}
            value={dueDate}
            onChange={handleDueDateChange}
          />
        </div>
      </MuiPickersUtilsProvider> */}
      <TextField
        className="mt-8 mb-16"
        label="Net Amount"
        id="extraShippingFee"
        variant="outlined"
        InputProps={{
          startAdornment: <InputAdornment position="start">$</InputAdornment>,
        }}
        value={netAmount}
        onChange={handleNetAmountChange}
        fullWidth
      />

      <TextField
        className="mt-8 mb-16"
        label="Tax Number"
        id="extraShippingFee"
        variant="outlined"
        InputProps={{
          startAdornment: <InputAdornment position="start">$</InputAdornment>,
        }}
        value={taxNumber}
        onChange={handleTaxAmountChange}
        fullWidth
      />

      <TextField
        className="mt-8 mb-16"
        label="Gross Amount"
        id="extraShippingFee"
        variant="outlined"
        InputProps={{
          startAdornment: <InputAdornment position="start">$</InputAdornment>,
        }}
        value={grossAmount}
        onChange={handleGrossAmountChange}
        fullWidth
      />

      <div className={classes.root}>
        <input
          accept="application/pdf"
          // className={classes.input}
          // multiple
          type="file"
          onChange={fileSelectedHandler}
        />
        {/* <label htmlFor="contained-button-file"> */}
        {/* <Button
            variant="contained"
            color="primary"
            size="large"
            className={classes.button}
            startIcon={<CloudUploadIcon />}
          > */}
        {/* Upload */}
        {/* </Button> */}
        {/* </label> */}
      </div>

      <motion.div
        className="flex"
        initial={{ opacity: 0, x: 20 }}
        animate={{ opacity: 1, x: 0, transition: { delay: 0.3 } }}
      >
        <Button
          className="whitespace-nowrap mx-4"
          variant="contained"
          color="secondary"
          // onClick={handleRemoveProduct}
          startIcon={<Icon className="hidden sm:flex">delete</Icon>}
        >
          Cancel
        </Button>
        <Button
          className="whitespace-nowrap mx-4"
          variant="contained"
          color="secondary"
          // disabled={_.isEmpty(dirtyFields) || !isValid}
          onClick={uploadHandler}
        >
          Create
        </Button>
      </motion.div>
    </>
  );
}

export default ShippingTab;
nhhxz33t

nhhxz33t1#

@hiba-youssef这不是问题,控制台日志记录formData总是给出空obj,但这并不意味着它是空的,要打印值,您可以使用get()方法,请参考此官方文档https://developer.mozilla.org/en-US/docs/Web/API/FormData/get
--编辑--根据您的 Postman 屏幕截图,您可以修改uploadHandler fn,如下所示

const uploadHandler = (event) => {
     const formData=new FormData();
     formData.append('grossAmount',grossAmount);
     formData.append('taxNumber',taxNumber);
     formData.append('dueDate',dueDate);
     formData.append('netAmount',netAmount);
     formData.append('issueDate',issueDate);
     formData.append('issueDate',issueDate);
     formData.append('invoice',file);
     // now the formData is as per postman screenshot. You can also add all keys to an array and loop it
    };
55ooxyrt

55ooxyrt2#

Thanks ,
working fine when i used => Object.fromEntries(formData.entries())
const uploadHandler = (event) => {
     const formData=new FormData();
     formData.append('grossAmount',grossAmount);
     formData.append('taxNumber',taxNumber);
     formData.append('dueDate',dueDate);
     formData.append('netAmount',netAmount);
     formData.append('issueDate',issueDate);
     formData.append('issueDate',issueDate);
     formData.append('invoice',file);
     console.log(Object.fromEntries(formData.entries()))
    };

相关问题