如何在fetchApi中使用express-fileupload

时间:2019-01-15 16:13:31

标签: javascript node.js reactjs express fetch-api

我正在尝试使用fetch上传文件,以便我可以等待项目完成处理,然后将用户转发到正确的页面。

我正在使用express-fileupload,并且已成功使用html内联表单直接上传了文件。

这是我为fetch设置的内容

上传组件

class Uploader extends PureComponent {
  async onSubmit(el) {
    el.preventDefault();

    const { currentTarget: target } = el;
    const manpowerUpload = target.querySelector('input');

    //manpowerUpload.files = files[..1 item];

    if(manpowerUpload.files && manpowerUpload.files.length > 0) {
      const fetchData = await fetch('http://localhost:5002/upload/manpower', {
        method: 'POST',
        headers: {
          "Content-Type": "text/csv",
        },
        body: manpowerUpload.files,
      });
    }
    //fetchData = 400 from server 
  }
  render(){
    return (
      <div data-testid="admin.productionAdmin.manpower">
        <form ref='manpowerUpload'
              id='manpowerUpload'
              action='http://localhost:8000/upload'
              method='post'
              encType="multipart/form-data"
              onSubmit={this.onSubmit}
        >
            <input
                accept={props.accept}
                className={classes.input}
                name={props.name}
                id="contained-button-file"
                multiple
                type="file"
           />
          <label htmlFor="contained-button-file">
               <Button variant="contained" component="span" className={classes.button}>
                  <FormattedMessage id={label} />
               </Button>
           </label>
          <Button type="submit" variant="outlined">Submit</Button>
        </form>
      </div>
    );
  }
};

Express

app.post('/upload/manpower', function(req, res) {
  if (!req.files)
    return res.status(400).json({message: 'No files were uploaded.', success: false});
});

0 个答案:

没有答案