【问题标题】:Uploading images from your React frontend to your Mongo db using express server使用快速服务器将图像从 React 前端上传到 Mongo db
【发布时间】:2020-07-09 14:35:18
【问题描述】:

我正在尝试使用后端的 multer 将图片从我的 React 前端发布到我的数据库,当我使用邮递员上传图片和数据时一切正常,但是,在我的 react 前端我发布时遇到了一些问题图片到数据库。前端代码如下

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

const Shoes = () => {

    const [name, setName] = useState("");
    const [price, setPrice] = useState("");

    const fileInput = React.createRef();

    const handleName = (e) => {
        setName(e.target.value);
    };
    const handlePrice = (e) => {
        setPrice(e.target.value);
    };

       const onSubmit = async (e) => {
        e.preventDefault();

        const product = {
            name: name,
            price: price,
            productImage: fileInput.current.files[0].name,
        };


        axios
            .post("http://localhost:5000/product/post", product)
            .then((res) => console.log(res.data))
            .catch((err) => console.log(err));

        alert(`Selected file - ${fileInput.current.files[0].name}`);
        console.log(fileInput.current.files[0]);
    };

    return (
        <div>
            <h2>Add Product</h2>

            <form onSubmit={onSubmit}>
                <input
                    type="text"
                    name="name"
                    value={name}
                    onChange={handleName}
                />
                <br />
                <input
                    type="text"
                    name="price"
                    value={price}
                    onChange={handlePrice}
                />
                <br />
                <input type="file" ref={fileInput} />
                <br />
                <input type="submit" value="Submit" />
            </form>

            <hr />
        </div>
    );
};

export default Shoes;

这就是我在 express 后端使用 multer 的方式

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

const Product = require("../models/Product");

const fileFilter = (req, file, cb) => {
    if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
        cb(null, true);
    } else {
        cb("JPEG and PNG only supported", false);
    }
};

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./uploads");
    },
    filename: function (req, file, cb) {
        cb(
            null,
            new Date().toISOString().replace(/:/g, "-") + file.originalname
        );
    },
});

const upload = multer({
    storage: storage,
    limts: {
        fileSize: 1024 * 1024 * 5,
    },
    fileFilter: fileFilter,
});

router.get("/", (req, res) => {
    Product.find()
        .select("name productImage -_id ")
        .then((pro) => res.json(pro))
        .catch((err) => res.json({ error: "could not get products", err }));
});

router.post("/post", upload.single("productImage"), async (req, res) => {
    console.log(req.file);
    const product = new Product({
        name: req.body.name,
        price: req.body.price,
        productImage: req.file,
    });

    try {
        const pro = await product.save();
        res.json(pro);
    } catch (err) {
        res.status(400).json({ error: "could not post shoe info", err });
    }
});


module.exports = router;


每当我从我的前端发送图片时,它会将图片发布为空,当我在控制台记录它时,我看到它以未定义的形式传递图片。所以我在想,也许它需要图像的路径,我一直在传递它的名字,但我似乎找不到从前端发布图像路径的方法。

提前致谢。

【问题讨论】:

    标签: node.js reactjs mongodb express


    【解决方案1】:

    JavaScript 中的文件上传是使用FormData 完成的。您没有使用 FormData 而是将数据作为对象发送。此外,您传递的只是文件名,而不是整个内容。

    const product = {
            name: name,
            price: price,
            productImage: fileInput.current.files[0] //.name,
        };
    

    查看SO Post

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 2020-01-09
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 2016-08-23
      相关资源
      最近更新 更多