ресурсы для загрузки изображения как атрибута элемента в приложении MERN - PullRequest
0 голосов
/ 04 августа 2020
• 1000 но не вышло, так как авторы приводят примеры, показывающие загрузку изображения как таковую, а не как атрибут объекта модели. Любые указатели на go по этому поводу будут оценены

это была моя попытка реализовать это

backend :

model

const mongoose = require('mongoose')

const productSchema = mongoose.Schema({
    name:{
        type:String,
        min:4
    },
    img: 
      { data: Buffer, contentType: String },
    price:{
        type:Number
    },
    available:{
        type:Boolean
    }
})

module.exports = mongoose.model('productdb', productSchema)

маршрут api

const express = require('express')
const router = express.Router()
const fs = require('fs')
const product = require('../models/products');
const { request } = require('http');
const { response } = require('express');


router.post('/add-product', (request,response) => {
    var newItem = new product({
        name:request.body.name,
        img:request.body.img,
        price:request.body.price,
        available:request.body.available
    });
    newItem.img.data = fs.readFileSync(request.body.img)
    newItem.img.contentType = 'image/png';
    newItem.save()
            .then((data)=>{
                response.json(data)
            })
            .catch((error)=> {
                response.json(error)
            })
   });

сервер. js

const express = require('express')
const app = express()
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const userURLS = require('./api/auth')
const multer = require('multer')
const productsURLS = require('./api/products')

dotenv.config()

mongoose.connect(process.env.DB_ACCESS, { useNewUrlParser: true }, () => {
    console.log('DB CONNECTED!')
})
app.use(express.json())
app.use('/user', userURLS)
app.use(multer({ dest: "./uploads/" ,
    rename:  (fieldname, filename) => {
      return filename;
    }
   }).single('photo'));
app.use('/products', productsURLS)


app.listen(7000, ()=> {
    console.log('Server is Up & Running!')
})

интерфейс :

AddProduct.jsx

import React, { Component } from 'react'
import axios from 'axios'

class AddProduct extends Component {
    constructor(){
        super()
        this.state = {
            //products:[],
            name:'',
            img:'',
            price:'',
            available:''
        }
        this.changedProductname = this.changedProductname.bind(this)
        this.changedProductimg = this.changedProductimg.bind(this)
        this.changedProductprice = this.changedProductprice.bind(this)
        this.changedProductavail = this.changedProductavail.bind(this)
        this.onSubmit = this.onSubmit.bind(this)

    }

    /*
    componentDidMount(){
        axios.get('http://localhost:7000/products')
            .then(response =>{
                if (response.data.length > 0) {
                    this.setState({
                        products:response.data.map(product => product.name),
                        name: response.data[0].name
                    })
                }
            })
    }
    */

    changedProductname(event){
        this.setState({
            name:event.target.value
        })
    }

    changedProductimg(event){
        this.setState({
            img:event.target.value
        })
    }
    
    changedProductprice(event){
        this.setState({
            price:event.target.value
        })
    }

    changedProductavail(event){
        this.setState({
            available:event.target.value
        })
    }

    onSubmit(event){
        event.preventDefault()
        const product = {
            name: this.state.name,
            img: this.state.img,
            price: this.state.price,
            available: this.state.available
        }
        console.log(product) 
        axios.post('http://localhost:7000/products/add-product', product)
            .then(response => console.log(response.data))
        window.location = '/'
    }
    

    render() { 
        return ( 
            <div>
                <div className="skewed"></div>
                <div className='container' style={{  paddingLeft:'300px', marginTop:'160px', marginBottom:'160px' }}>
                    <div className="card shadow " style={{ width:'520px', height:'600px' , borderRadius:'15px' , border:'none'}}>
                    <form onSubmit={this.onSubmit} method="post" style={{ width:'380px', textAlign:'', marginLeft:'70px', paddingTop:'90px'}}>
                        <h3 style={{  paddingBottom:'30px' }}>Add product</h3>
                        <div className="form-group">
                            <label htmlFor="name">Name</label>
                            <input onChange={ this.changedProductname } value={ this.state.name } type="text" className="form-control" id='name'/>
                        </div>
                        <div className="form-group">
                            <label htmlFor="img">Image</label>
                            <input onChange={ this.changedProductimg } value={ this.state.img } type="file" class="form-control-file" id='img'/>
                        </div>
                        <div className="form-group">
                            <label htmlFor="price">Price</label>
                            <input onChange={ this.changedProductprice } value={ this.state.price } type="text" className="form-control" id='price'/>
                        </div>
                        <div className="form-group form-check">
                            <input onChange={ this.changedProductavail } value={ this.state.available } type="checkbox" class="form-check-input" id="avail"/>
                            <label class="form-check-label" htmlFor="avail">Available</label>
                        </div>
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </form>
                    </div>
                </div>
            </div>
         );
    }
}
 
export default AddProduct;
...