【问题标题】:Accessing Upload Data in React From Multer Node Server从 Multer 节点服务器访问 React 中的上传数据
【发布时间】:2019-01-05 02:24:33
【问题描述】:

所以我想出了如何使用 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}`));

我的反应文件:

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;

【问题讨论】:

    标签: node.js reactjs upload multer


    【解决方案1】:

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

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

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

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

    具体针对您的情况,您可以持有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} /> }
    

    这是一个非常简单的例子,当你的应用变大时,逻辑会更复杂。

    【讨论】:

      猜你喜欢
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 2018-12-04
      • 2017-10-20
      • 1970-01-01
      • 2020-07-16
      相关资源
      最近更新 更多