使用Node.js,Express,Mongoose和React将图像上传到MongoDB

时间:2020-03-17 12:33:27

标签: node.js reactjs mongodb express mongoose

我正在使用一个简单的Web应用程序来练习我在Web开发中新开发的技能。我正在尝试使用Nodejs,Express,Mongoose和React将一本书的图像及其图像上载到MongoDB。到目前为止,我可以通过单击“提交”按钮将所有信息上传到MongoDB。但是每当我尝试将图像添加到猫鼬模式时,发布请求都无法正常工作。我无法弄清楚我的代码存在的问题。 这是Book模型的代码:

const mongoose = require("mongoose");

const BookSchema = new mongoose.Schema({
  image: {
    data: Buffer,
    contentType: String
  },
  title: {
    type: String,
    required: true
  },
  isbn: {
    type: String,
    required: true
  },
  author: {
    type: String,
    required: true
  },
  description: {
    type: String
  },
  published_date: {
    type: Date
  },
  publisher: {
    type: String
  },
  updated_date: {
    type: Date,
    default: Date.now
  }
});

module.exports = Book = mongoose.model("book", BookSchema);

以下是发布请求的代码:

router.post("/", (req, res) => {
  var title= req.body.title;
  var isbn = req.body.isbn;
  var author = req.body.author;
  var description = req.body.description;
  var published_date= req.body.published_date;
  var publisher = req.body.publisher;
  var updated_date = req.body.updated_date;

  var imgPath = req.file.path;
  var image = Book.image.data = fs.readFileSync(imgPath);
  Book.image.contentType = 'image/jpg';

  var newBook = {image: image, title: title, isbn: isbn, author: author, description: description, 
  published_date: published_date, publisher: publisher, updated_date: updated_date};
  Book.create(newBook, function(err, newlyCreated){
    if (err) {
        console.log(err);
    } else {
        console.log(newlyCreated);
    }
 });

})

这是使用React的前端代码:

import React, { Component } from "react";
import { Link } from "react-router-dom";
import "../App.css";
import axios from "axios";

class CreateBook extends Component {
  constructor() {
    super();
    this.state = {
      image: "",
      title: "",
      isbn: "",
      author: "",
      description: "",
      published_date: "",
      publisher: ""
    };
    this.onFileChange = this.onFileChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

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

  onFileChange = e => {
    this.setState({ [e.target.name]: e.target.files[0] })
  }

  onSubmit = e => {
    e.preventDefault();
    const formdata = new FormData()

    formdata.append('image', this.state.image)
    formdata.append('title', this.state.title);
    formdata.append('isbn', this.state.isbn,);
    formdata.append('author', this.state.author);
    formdata.append('description', this.state.description);
    formdata.append('published_date', this.state.published_date);
    formdata.append('publisher', this.state.publisher);


    axios
      .post("http://localhost:8082/api/books", formdata)
      .then(res => {
        console.log(res);
        this.setState({
          image: "",
          title: "",
          isbn: "",
          author: "",
          description: "",
          published_date: "",
          publisher: ""
        });
        this.props.history.push("/");
      })
      .catch(err => {
        console.log("Error in CreateBook!");
      });
  };

  render() {
    return (
      <div className="CreateBook">
        <div className="container">
          <div className="row">
            <div className="col-md-8 m-auto">
              <br />
              <Link to="/" className="btn btn-outline-warning float-left">
                Show BooK List
              </Link>
            </div>
            <div className="col-md-8 m-auto">
              <h1 className="display-4 text-center">Add Book</h1>
              <p className="lead text-center">Create new book</p>

              <form noValidate onSubmit={this.onSubmit}>
                <div className="form-group">
                  <input
                    type="file"
                    placeholder="Browse Image"
                    name="image"
                    className="form-control"

                    onChange={this.onFileChange}
                  />
                </div>
                <button type="button" className="btn btn-primary mb-3">
                  Upload
                </button>
                <br />
                <div className="form-group">
                  <input
                    type="text"
                    placeholder="Title of the Book"
                    name="title"
                    className="form-control"
                    value={this.state.title}
                    onChange={this.onChange}
                  />
                </div>
                <br />

                <div className="form-group">
                  <input
                    type="text"
                    placeholder="ISBN"
                    name="isbn"
                    className="form-control"
                    value={this.state.isbn}
                    onChange={this.onChange}
                  />
                </div>

                <div className="form-group">
                  <input
                    type="text"
                    placeholder="Author"
                    name="author"
                    className="form-control"
                    value={this.state.author}
                    onChange={this.onChange}
                  />
                </div>

                <div className="form-group">
                  <input
                    type="text"
                    placeholder="Describe this book"
                    name="description"
                    className="form-control"
                    value={this.state.description}
                    onChange={this.onChange}
                  />
                </div>

                <div className="form-group">
                  <input
                    type="date"
                    placeholder="published_date"
                    name="published_date"
                    className="form-control"
                    value={this.state.published_date}
                    onChange={this.onChange}
                  />
                </div>
                <div className="form-group">
                  <input
                    type="text"
                    placeholder="Publisher of this Book"
                    name="publisher"
                    className="form-control"
                    value={this.state.publisher}
                    onChange={this.onChange}
                  />
                </div>

                <input
                  type="submit"
                  className="btn btn-outline-warning btn-block mt-4"
                />
              </form>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default CreateBook;

我将非常感谢您的任何建议。预先感谢。

1 个答案:

答案 0 :(得分:0)

如果您使用的格式为'jpeg / png'的图像且小于16mb,则可以使用此github存储库,它是一个模块,可帮助轻松地将图像保存到mongodb,而无需GRIDFS的复杂性,但是如果文件大于16mb,则需要使用GRIDFS,

这是github存储库中小于16 mb的图像的链接(也可以很好地与react配合使用)

https://github.com/saran-surya/Mongo-Image-Converter

希望这会有所帮助:)