从React上传多个图像到Multer

时间:2018-12-25 15:20:10

标签: node.js reactjs file-upload multer uploading

我正在使用react,multer和node.js

我正在用一种方法上传一张图像,没有任何问题,但是 我无法上传多个文件,也没有任何错误。

我用Postman测试了后端node.js代码,它可以正常工作(它可以上传 多张图片),但是当我尝试使用react时,它会失败。我得到的req.files是空数组。

请在下面查看我的代码:

node.js代码:

const multer = require("multer");

const storage = multer.diskStorage({

  destination: (req, file, cb) => {

    //uploaded files destination
    cb(null, "./client/public/images");
  },
  filename: (req, file, cb) => {

    const newFilename = `${new Date().getDate()}-${new Date().getMonth() +
      1}-${new Date().getFullYear()}-${file.originalname}`;
    cb(null, newFilename);
  }
});

const upload = multer({ storage }).array('files');

const Product = require("../../modules/products");

router.post("/addnew", upload, (req, res) => {

     let products = JSON.parse( // Saving products database
       fs.readFileSync(path.join(__dirname, "../../db") + "/products.json")
     );

     const product = new Product(req.body, req.files, uuidv4());   // Creating new Product

     products.unshift(product);    // Adding new product to products array
     products = JSON.stringify(products);     // Updating products database

     fs.writeFileSync(
       path.join(__dirname, "../../db") + "/products.json",
       products
     );

     return res.json(product);
});

反应码

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

export default class NewProduct extends Component {
  state = {
    files: "",
  };

  onChangeHandler = e => {
    this.setState({ files: e.target.files });
  };

  onSubmitHandler = e => {
    e.preventDefault();

    let formData = new FormData();

    formData.append("files", this.state);

    axios
      .post("/api/products/addnew", formData)
      .then(res => {
      })
      .catch(err => {
        console.log(err);
      });
  };

  render() {
    return (

      <form className="form-product" encType="multipart/form-data" onSubmit={this.onSubmitHandler} >

        <div className="form-row">
          <label htmlFor="customFile">Product Images</label>

          <div className="custom-file col-md-12">
            <input type="file" multiple className="custom-file-input" id="customFile" name="files" onChange={this.onChangeHandler} />
            <label className="custom-file-label" htmlFor="customFile">
              Choose Main Photo
          </label>
          </div>
        </div>

        <div className="col-md-12 text-center">
          <button type="submit" className="btn btn-primary new-product-button">
            Add
        </button>
        </div>

      </form>

    )
  }
}

0 个答案:

没有答案