node.js - 从 Multer Node 服务器访问 React 中的上传数据

标签 node.js reactjs upload multer

所以我想出了如何使用 React 和 Node.js 上传文件。它似乎有效,但我对这些东西仍然很陌生,而且我不太明白如何访问我刚刚在 React 中上传的文件。我想要拥有它,以便您使用 React 中的表单上传 zip 文件,然后我想让一些脚本解压缩上传的文件并对内容执行一些操作。我的文件上传正确,但我不知道上传后如何将文件名数据传递到 React 中..

我的服务器文件:

const port = process.env.PORT || 5000;
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const uuidv4 = require('uuid/v4');
const path = require('path');

const storage = multer.diskStorage({
  destination: (req, file, cb) => {

    cb(null, './src/uploads');
  },
  filename: (req, file, cb) => {


    const newFilename = `${uuidv4()}${path.extname(file.originalname)}`;
    cb(null, newFilename);
  },
});

var fileFilter = function (req, file, cb) {

   if (
    file.mimetype !== 'application/zip'
    ) {

      req.fileValidationError = 'goes wrong on the mimetype';
      return cb(new Error('mimetype does not match application/zip. upload rejected'));
   }
   console.log('>> fileFilter good = ',file.mimetype)
   cb(null, true);
  }

const upload = multer({ storage: storage, fileFilter: fileFilter });

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', upload.single('selectedFile'), (req, res) => {

  res.send();
});


app.listen(port, () => console.log(`Server listening on port ${port}`));

我的 react 文件:

import React, { Component } from 'react';
import axios from 'axios';

class UserForm extends Component {
  constructor() {
    super();
    this.state = {
      description: '',
      selectedFile: '',
    };
  }

  onChange = (e) => {
    switch (e.target.name) {
      case 'selectedFile':
        this.setState({ selectedFile: e.target.files[0] });
        break;
      default:
        this.setState({ [e.target.name]: e.target.value });
    }
  }

  onSubmit = (e) => {
    e.preventDefault();
    const { description, selectedFile } = this.state;
    let formData = new FormData();

    formData.append('description', description);
    formData.append('selectedFile', selectedFile);

    console.log('form data ',formData)

    axios.post('/', formData)
      .then((result) => {
        console.log('>> (onSubmit) file upload result = ',result);
        // access results...
      })
      .catch(function (error) {
        console.log('>> ERROR FILE UPLAOD ',error);
        alert('File upload failed. Please ensure you are uploading a .zip file only')
      })
  }

  render() {
    const { description, selectedFile } = this.state;
    return (
      <form onSubmit={this.onSubmit}>
        <input
          type="text"
          name="description"
          value={description}
          onChange={this.onChange}
        />
        <input
          type="file"
          name="selectedFile"
          onChange={this.onChange}
        />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

export default UserForm;

最佳答案

在您的情况下,您上传​​的是单个文件。所以你需要从你的 / 返回它路线是这样的

app.post('/', upload.single('selectedFile'), (req, res) => {
  res.send( req.file );
});

当您使用 Multer 并上传这样的文件时,则 req.file此处将是您上传的文件,即selectedFile 。因此,您需要将其归还以在您想要的任何地方使用。

这个req.file有一些信息,如 originalname, filename, path等等。您可以在前端使用这些信息。例如,您可以抓取 path (这是上传文件的完整路径)然后在 <img> 中使用它元素。

根据您的情况,您可以持有 imagePath状态:

this.state = {
      description: '',
      selectedFile: '',
      imagePath: '',
};

然后更新您的 axois' .then 中的状态方法:

axios.post('/', formData)
    .then((result) => {
        this.setState({imagePath: result.data.path})
})
....

并在您的组件中使用它:

{this.state.imagePath && <img src={this.state.imagePath} /> }

这是一个非常简单的示例,当您的应用变得更大时,逻辑可能会更加复杂。

关于node.js - 从 Multer Node 服务器访问 React 中的上传数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51566797/

相关文章:

sql - 使用 Coldfusion 上传时存储文件名

php - 带有附加数据的 jQuery 文件上传

Node.js、Express.js - 意外标记 {

javascript - 即使不满足 MySQL "where"子句,它也会返回一行

node.js - 如何在node.js中获取CNAME记录的权威TTL值?

reactjs - 如何在 material-ui 中创建非模态对话框

javascript - 填充条件失败

javascript - typescript 中的 useContext 和 useReducer

reactjs - 将 React 值从子级传递给父级

xcode - 错误 itms-90451 "CFBundleIdentifier Collision Error"