首页 > 解决方案 > 反应:req.files 返回空白数组

问题描述

我有 Node.js 应用程序,由 express 提供服务,我的前端是用 React.js 制作的。我正在创建一个需要上传多个图像的组件。问题出在客户端发送数据后 req.files 返回一个空白数组。我还使用邮递员检查后端,它工作正常。唯一的问题是前端。

Client-side
const UserPost = () => {
  const [postImageCollection, setPostImageCollection] = useState([]);


  const handleImageCollection = async (e) => {
    e.preventDefault();
    const fdPayload = new FormData();
    for (let i = 0; i < postImageCollection.length; i++) {
      fdPayload.append('postImageCollection', postImageCollection[i]);
    }

    try {
      await axios({
        method: 'POST',
        url: 'http://localhost:5000/user/posts',
        data: fdPayload,
        headers: {
          'content-type': 'multipart/form-data',
        },
      }).then((res) => {
        console.log(res);
      });
    } catch (error) {
      console.log(error.response);
    }
  };

  const handleChangeImageCollection = (e) => {
    const newArray = [...postImageCollection];
    for (let i = 0; i < e.target.files.length; i++) {
      newArray.push({ src: URL.createObjectURL(e.target.files[i]) });
    }
    setPostImageCollection(newArray);
    if (newArray.length > 5) {
      setCurrentImageHide('+' + (newArray.length - imagePerPost));
    }
  };

  return (
    <Container
      component='div'
      className={classes.userPostContainer}
      style={{ padding: '0', margin: '0' }}
    >
      <Card className={classes.userPostCard} style={{ boxShadow: 'none' }}>
        <CardContent style={{ padding: '0 0 1.5em 0' }}>
          <form noValidate onSubmit={handleImageCollection}>
            <Grid container>
              <Grid
                xs={12}
                className={classes.postPhotoContainer}
                style={{ padding: '0' }}
              >
                <ImageList
                  postImageCollection={currentImage}
                  currentImageHide={currentImageHide}
                />
                <input
                  accept='image/*'
                  id='postImageCollection-file-button'
                  type='file'
                  name='postImageCollection'
                  onChange={handleChangeImageCollection}
                  multiple
                  style={{ display: 'none' }}
                />
                <label htmlFor='postImageCollection-file-button'>
                  <ImageIcon />
                  Photo
                </label>
              </Grid>
              <Button
                type='submit'
                variant='contained'
                className={classes.button}
                style={{ width: '60%', marginBottom: '2.5rem' }}
              >
                Upload
              </Button>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Container>
  );
};

Backend
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/images/post');
  },
  filename: function (req, file, cb) {
    cb(
      null,
      `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
    );
  },
});

const upload = multer({
  storage,
  limits: {
    fileSize: '2mb',
  },
  fileFilter: (req, file, cb) => {
    if (
      file.mimetype == 'image/png' ||
      file.mimetype == 'image/jpg' ||
      file.mimetype == 'image/jpeg'
    ) {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
    }
  },
});

router.post(
  '/user/posts',
  upload.array('postImageCollection', 12),
  function (req, res, next) {
    console.log(req);
  }
);

注意: postImageCollection 是字段名,也是猫鼬模式中的字段名

谢谢!

标签: reactjsaxios

解决方案


推荐阅读