使用multer上传文件

时间:2019-07-14 17:04:27

标签: node.js reactjs multer

我正在尝试制作一个可以使用express和multer上传文件的Web应用程序,但是我遇到的问题是没有文件上传并且req.file始终未定义。我已经检查了多种解决方案,但是都没有他们正在工作。

我的reactjs组件如下:



onSubmit(e) {
    e.preventDefault();

    const productData = {
      name: this.state.name,
      image: this.state.image,
      description: this.state.description,
      category: this.state.category,
      quantity: this.state.quantity,
      price: this.state.price
    };

    console.log(productData.image);

    this.props.createProduct(productData, this.props.history);
  }



onChange(e) {
    this.setState({ [e.target.name]: e.target.value });
  }



<form onSubmit={this.onSubmit} encType="multipart/form-data">
  <UploadImage
     name="image"
     value={this.state.image}
     onChange={this.onChange}
     error={errors.image}
     type="file"
     info="Upload image of the product"
    />
   <input
      type="submit"
      value="Submit"
      className="btn btn-info btn-block mt-4"
    />
</form>

我的路由器文件如下:

const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");

//Loading validation function

const validateProductInput = require("../../validation/product.js");

//Load product model
const Product = require("../../models/Product");

//@route GET api/products/test
//@desc Test product route
//@access public
router.get("/test", (req, res) => res.json({ msg: "Profile Works" }));

//Creating a multer API to upload images

const storage = multer.diskStorage({
  destination: "../../uploads",
  filename: function(req, file, cb) {
    cb(
      null,
      file.fieldname + "." + Date.now() + path.extname(file.originalname)
    );
  }
});

//Init Upload
const upload = multer({
  storage: storage
});

//@route    Post api/products/add
//@desc     Add product
//@access   Private
router.post("/add", upload.single("image"), (req, res) => {
  const { errors, isValid } = validateProductInput(req.body);

  if (!isValid) {
    //Return any erros with 400 status
    return res.status(400).json(errors);
  }

  console.log("File: ", req.file);

  Product.findOne({
    name: req.body.name
  }).then(product => {
    if (product) {
      errors.exist = "Item Already Exists";
      return res.status(400).json(errors);
    } else {
      // let image_path = req.body.image;
      // image_path = image_path.replace(
      //   /fakepath/g,
      //   "projects\\e-commerce\\MERN-eCommerce\\client\\src\\components\\dashboard\\images"
      // );

      const newProduct = new Product({
        name: req.body.name,
        image: req.body.image,
        description: req.body.description,
        category: req.body.category,
        quantity: req.body.quantity,
        price: req.body.price
      });
      newProduct
        .save()
        .then(product => res.json(product))
        .catch(err => res.status(404).json());
    }
  });
});

//上传图片组件

const UploadImage = ({ name, value, type, error, info, onChange }) => {
  // Add the following code if you want the name of the file appear on select
  $(".custom-file-input").on("change", function() {
    var fileName = $(this)
      .val()
      .split("\\")
      .pop();
    $(this)
      .siblings(".custom-file-label")
      .addClass("selected")
      .html(fileName);
  });

  return (
    <div className="custom-file">
      <input
        className={classnames(
          "custom-file-input form-control form-control-lg",
          {
            "is-invalid": error
          }
        )}
        name={name}
        type={type}
        value={value}
        onChange={onChange}
      />
      <label className="custom-file-label">Choose file</label>

      {info && <small className="form-text text-muted">{info}</small>}
      {error && <div className="invalid-feedback">{error}</div>}
    </div>
  );
};

UploadImage.propTypes = {
  name: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  value: PropTypes.string.isRequired,
  info: PropTypes.string,
  error: PropTypes.string,
  onChange: PropTypes.func.isRequired
};

export default UploadImage;

console.log(“ File:”,req.file);始终未定义,并且没有文件上传到上载目录

0 个答案:

没有答案