有没有办法我可以在反应中处理文件上传

is there a way i can handle file upload in react

我正在尝试将这些字段从 React 提交到节点服务器,我可以提交其余的输入字段和 select 选项,但我无法上传照片,而且我可以将所有字段(包括照片)上传到服务器使用 POSTMAN

 // fields to submit to node server
    state = {
        data: {
          fullName: '',
          email: '',
          phoneNumber: '',
          branchId: '',
          jobId: '',
          salary: '',
          image: '',
          // startDate: '',
        },
    
    // onChange handler
    
    handleChange = ({ currentTarget: input }) => {
        //clone the errors
        const errors = { ...this.state.errors }
        //validate the input
        const errorMessage = this.validateProperty(input)
        //
        if (errorMessage) errors[input.name] = errorMessage
        //
        else delete errors[input.name]
    
        //clone the data
        const data = { ...this.state.data }
    
        //override the state data with the input value
        data[input.name] = input.value
        // update the state with the data and errors
        this.setState({ data, errors })
      }
    // submit or onClick handler
    
    doSubmit = async () => {
        const { data } = this.state
    
        const fd = new FormData()
        fd.append('fullName', data.fullName)
        fd.append('email', data.email)
        fd.append('phoneNumber', data.phoneNumber)
        fd.append('branchId', data.branchId)
        fd.append('jobId', data.jobId)
        fd.append('salary', data.salary)
        fd.append('image', data.image)
    
        // fd.append()
    
        await saveEmployee(fd)
        this.props.history.push('/employees')
      }

我猜 image 输入是一个 file 字段?

您现在正在存储文件字段的 input#value,但实际上您正在寻找 input#files[0] 值。这包含对实际文件的引用,可以附加到表格中。

handleChange = ({ currentTarget: input }) => {
    //clone the errors
    const errors = { ...this.state.errors }
    //validate the input
    const errorMessage = this.validateProperty(input)
    //
    if (errorMessage) errors[input.name] = errorMessage
    //
    else delete errors[input.name]

    //clone the data
    const data = { ...this.state.data }

    //override the state data with the input value
    data[input.name] = input.type === 'file' ? input.files[0] : input.value
    // update the state with the data and errors
    this.setState({ data, errors })
  }

这可以通过以下方式实现:

在服务器端使用“multer”来处理上传的文件: https://expressjs.com/en/resources/middleware/multer.html

现在创建一个端点来处理您的文件上传。

例如(服务器代码):

// Import Multer
const multer = require("multer");

// Express
let app = express();

// upload destination
const uploadLocation = multer({ dest: "uploads/" });

// Endpoint
app.post(
  "/upload",
  // Here pass the name of file that you've set in FormData. In your 
  // case its "image", as your appending file data as image in your 
  // code. 
  uploadLocation.single("image"),
  async (req, res) => {
  // get file from req
  const file = req.file;
  // This is your uploaded file
  console.log(file);
  // You can handle other data here...
  res.status(200).send({ path: `uploads/${file.filename}` });
  }
);

现在使用此端点发送您的发件人数据。

例如(client端代码在Javascript):

 const data = await fetch(
        `${process.env.REACT_APP_SERVER_URL}/upload`,
        {
          method: "POST",
          credentials: "include",
          headers: {},
          // Send your form data like this to server
          body: formData,
        }
      );
      const { path } = await data.json();
      // This is your path of uploaded file          
      console.log(path)