【问题标题】:Uploading Image With Reactjs and Mongo使用 Reactjs 和 Mongo 上传图片
【发布时间】:2022-07-17 23:08:34
【问题描述】:

我想创建一个简单的应用程序来使用 React 和 Express 将带有其配置文件的图像上传到 mongoDB。我遵循了许多教程,但它是无用的。我总是遇到“TypeError:无法读取未定义的属性(读取'文件')” 这是 React Js 代码(我不想使用 ):

    function App() {

  const [file, setFile] = useState('');

  onchange=(e)=>{
    setFile(e.target.files[0])
  }

  onsubmit=(e)=>{
    e.preventDefault()
    const data = new FormData()
    data.append('file',file)
    axios.post('http://localhost:8000/addbook',data)
    .then((res)=>{
        console.log('Saved Successfully')
    })
    .catch((err)=>{
    console.log('Error')
    })
  }

  return (
    <div className="App">
        <input type='file'name="file"  onChange={onchange} />
        <input  type='submit' onClick={onsubmit}/>
      
    </div>
  );
}

export default App;

这是图书架构(猫鼬)

const BookSchema = new Schema({
    bookname:{
        type:String
    },
    bookimage:{
       type: String
    },
    authorname:{
        type:String
    },
    isbn:{
        type:String
    },
    category:{
        type:String
    },
    language:{
        type:String
    },
    rating:{
        type:Number
    },
    numberofrating:{
        type:Number
    }

这是后端(路由器)

const express= require('express')
const { append } = require('express/lib/response')
const UserRouter=express.Router()
const Book = require('../Schemas/BookSchema')

UserRouter.use(express.json())
const multer=require('multer')



UserRouter.use(express.static(__dirname+'./public/'))

var Storage= multer.diskStorage({
    destination:"./public/uploads/",
    filename: (req, file, cb)=>{
       cb(null, file.fieldname+" "+Date.now()+path.extname(file.originalname))
    }
  }
);

var upload = multer({
    storage:Storage
  }).single('file');

UserRouter.post('/addbook',upload,(req,res)=>{
   const newbook = new Book({
    "bookname":'MyBook',
    "bookimage":req.files.file,
    "authorname":'Mansour',
    "isbn":11122,
    "category":'English',
    "language":'English',
    "rating":0,
    "numberofrating":0
   })
   newbook.save()
   .then((res)=>{
       console.log('Saved Successfully')
   })
   .catch((err)=>{
    console.log('Error')
   })
    
})


module.exports=UserRouter

我是一个绝对的初学者,所以这可能是一件容易的事 我也想知道,为什么要创建一个名为 Uploads 的文件夹。我想将图像存储在 mongodb 中,然后能够将其与要显示的书籍数据一起检索。注意: 当我打印(req.files)时,它是未定义的

【问题讨论】:

  • 嗨!您是否设法解决了问题?

标签: reactjs mongodb


【解决方案1】:

将 file.fieldname 更正为 file.filename。

并尝试 "bookimage":fs.readFileSync("uploads/" + req.file.filename)

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 2017-08-03
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2022-11-30
    • 2019-03-09
    相关资源
    最近更新 更多