【问题标题】:How to fix upload files in React + Node?如何修复 React + Node 中的上传文件?
【发布时间】:2018-11-25 14:34:06
【问题描述】:

我尝试将文件上传到服务器,但收到错误 500。

在前端(React)我使用 axios:

class InputFile extends Component {
  constructor(props) {
    super(props);
    this.state = { selectedFile: null };
    this.handleUploadFile = this.handleUploadFile.bind(this);
    this.handleUpload = this.handleUpload.bind(this);
  }

  handleUploadFile(event) {
    this.setState({
      selectedFile: event.target.files[0]
    });
  }

  handleUpload() {
    const data = new FormData();

    data.append('file', this.state.selectedFile, this.state.selectedFile.name);
    axios
        .post('http://127.0.0.1:8000/upload', data)
        .then(res => {
          console.log(res.statusText);
        });
  }

  render() {
    return (
      <div>
        <input name='file' type='file' formEncType='multipart/form-data'
          onChange={this.handleUploadFile} multiple
        />
      </div>
      )
     }
    }

在后端(节点)我试图将文件保存在文件夹中:

app.route('/upload')
    .post((req, res, next) => {
      const uploadFile = req.files.file;
      const fileName = req.files.file.name;

      uploadFile.mv(
          `uploadFiles/${fileName}`,
          (err) => {
            if (err) {
              return res.status(500).send(err);
            }

            res.json({
              file: `uploadFiles/${req.files.file.name}`
            });
          },
        );
    });

实际上我在控制台中收到错误:

未捕获(承诺中)错误:请求失败,状态码为 500

而后端的 req.filesundefined。我该如何解决?应该可以一次上传一个或多个文件

在前端我使用:“axios”:“^0.18.0”,

在后端我使用:“express-fileupload”:“^1.0.0”

【问题讨论】:

标签: node.js reactjs file-upload upload


【解决方案1】:

问题在于后端的目录路径。我改变了这个:

`uploadFiles/${fileName}`,

到我计算机上的完整路径

/var/*/uploadFiles/${fileName},

我也忘了添加这个:

const fileUpload = require('express-fileupload');

app.use(fileUpload());

【讨论】:

    猜你喜欢
    • 2015-03-24
    • 1970-01-01
    • 2019-09-17
    • 2021-04-09
    • 2020-10-22
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2021-08-29
    相关资源
    最近更新 更多