【问题标题】:is there a way i can handle file upload in react有没有办法我可以在反应中处理文件上传
【发布时间】:2021-09-15 15:59:05
【问题描述】:

我正在尝试将这些字段从 react 提交到节点服务器,我可以提交其余的输入字段并选择选项,但我无法上传照片,而且我可以使用 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')
      }

【问题讨论】:

    标签: node.js reactjs mern


    【解决方案1】:

    我猜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 })
      }
    

    【讨论】:

      【解决方案2】:

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

      在服务器中使用“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}` });
        }
      );
      

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

      例如(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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-12
        • 1970-01-01
        • 2022-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多