【问题标题】:Express multer is returning undefined on req.fileExpress multer 在 req.file 上返回 undefined
【发布时间】:2019-01-16 04:54:19
【问题描述】:

我正在尝试将文件传递给节点,并且 express 不会将其存储在 req.body 中,因此我正在使用 multer 中间件,但每当我登录 req.file 时,我都会变得不确定。我不确定我做错了什么。

反应/index.js

fileSelectHandler = e => {
  axios.post("/api/upload", { profilePic: e.target.files[0] });
  this.setState({ profilePic: e.target.files[0] });
};

render() {
  return (
    <input
      onChange={event => this.fileSelectHandler(event)}
      name="profilePic"
      type="file"
    />
  );
}

节点/index.js

app.post("/api/upload", upload.single("profilePic"), (req, res) =>
  console.log(req.file)
);

【问题讨论】:

    标签: javascript reactjs express multer


    【解决方案1】:

    您可以改用FormData 来上传文件。

    fileSelectHandler = e => {
      const formData = new FormData();
      const profilePic = e.target.files[0];
    
      formData.append("profilePic", profilePic);
    
      axios.post("/api/upload", formData);
      this.setState({ profilePic });
    };
    

    【讨论】:

      【解决方案2】:

      我认为您需要将文件作为表单数据类型上传,如下所示。

      fileSelectHandler = e => {
      const formData = new FormData();
      formData.append(‘profilePic’,e.target.files[0]);
      
      const config = {
          headers:{
              ‘content-type’:’multipart/form-data’
              }
          }
      axios.post("/api/upload", formData, config);
      this.setState({ profilePic: e.target.files[0] });
      };
      

      希望对您有所帮助。

      【讨论】:

        【解决方案3】:

        另一个多文件输入的例子。在 Express JS 上测试

        function uploadImages(post) {
            return new Promise((resolve, reject) => {
                const formData = new FormData();
                for( var i = 0; i < post.length; i++ ){
                    formData.append('multifiles', post[i]);
                }
                let jsonPost = {
                    method: POST_REQUEST,
                    url: UPLOAD_FILE_URL,
                    data: formData,
                    headers: {
                        'content-type': 'multipart/form-data',
                    }
                };
                fetchData(jsonPost)
                    .then(res => {
                        console.log("RESULT uploadImages: ", res.data);
                        resolve(res.data);
                    })
                    .catch(reject);
            });
        }
        

        【讨论】:

          猜你喜欢
          • 2020-08-07
          • 2018-08-19
          • 2022-08-19
          • 1970-01-01
          • 1970-01-01
          • 2017-01-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多