0% found this document useful (0 votes)
25 views5 pages

Imagenes

The document describes the backend and frontend code for an image uploading and display feature. It includes: 1) Backend controllers to handle uploading images to the server and retrieving images from the database. 2) A database model defining the image table. 3) A React component for adding images with a preview that calls the backend upload API. 4) Another React component to display retrieved images by calling the backend get images API. 5) Notes on backend configuration including installing multer for uploads and setting the correct body parsers.

Uploaded by

el 21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views5 pages

Imagenes

The document describes the backend and frontend code for an image uploading and display feature. It includes: 1) Backend controllers to handle uploading images to the server and retrieving images from the database. 2) A database model defining the image table. 3) A React component for adding images with a preview that calls the backend upload API. 4) Another React component to display retrieved images by calling the backend get images API. 5) Notes on backend configuration including installing multer for uploads and setting the correct body parsers.

Uploaded by

el 21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

Controller de la imagen:

export const GetimgOrg = async(req, res) => {


try {
let Data = await ImgOrg.findAll();
res.json(Data);
} catch (error) {
console.log(error);
}
}

export const uploadImgOrg = async (req, res) => {


try {
console.log("Llega al controller");
console.log(req.file);

if (req.file === undefined) {


return res.send(`You must select a file.`);
}

ImgOrg.create({
type: req.file.mimetype,
name: req.file.originalname,
ImgOrg: fs.readFileSync('resources/statict/assets/uploads/' +
req.file.filename
),
}).then((ImgOrg) => {
fs.writeFileSync('resources/statict/assets/uploads/' + ImgOrg.filename,
ImgOrg.ImgOrg
);

return res.send(`File has been uploaded.`);


});
} catch (error) {
console.log(error);
return res.send(`Error when trying upload images: ${error}`);
}
};

Modelo de la imagen:
// It first imports the Sequelize library and the database configuration.
import { Sequelize } from "sequelize";
import db from "../config/database.js";

const {DataTypes} = Sequelize;


// Define the "ImgOrg" model using Sequelize
const ImgOrg = db.define('imgOrg', {
idImgOrg:{
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name:{
type: DataTypes.STRING
},
ImgOrg:{
type: DataTypes.BLOB
},
type:{
type: DataTypes.STRING,
}
},{
freezeTableName: true,
timestamps: false
});
// Synchronize the model with the database
(async () => {
await db.sync();
})();
// Export the "ImgOrg" model
export default ImgOrg;

React Añadir imagen:


import React, { useState } from 'react'
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import 'bootstrap/dist/css/bootstrap.min.css';
import Col from 'react-bootstrap/esm/Col';
import Row from 'react-bootstrap/esm/Row';

const AddImage = () => {


const [userNIF, setUserNif] = useState('');
const [image, setImage] = useState('');
const [data, setData] = useState('');
const [selectedImages, setSelectedImages] = useState('');
const [previewImages, setPreviewImages] = useState('');
const [msg, setMsg] = useState('');
const history = useNavigate();

const PreviewImg = async (e) => {


setSelectedImages(e.target.files[0]);
const inputFile = e.target.files[0];
if (inputFile) {
const reader = new FileReader();
reader.onload = (e) => {
setPreviewImages([e.target.result]);
};
reader.readAsDataURL(inputFile);
}

};

const Add = async (e) => {


e.preventDefault();
console.log(previewImages);
const formData = new FormData();
formData.append('file', selectedImages);

axios.post('/upload', formData)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
};
return (
<div style={{
backgroundImage:
`url("https://sirc.ca/wp-content/uploads/2020/03/AdobeStock_298604606-
scaled.jpeg")`,
backgroundSize: "cover"
}}>
<div className='bg-success bg-opacity-25'>
<div className= "form-container vh-100 d-flex justify-content-
center align-items-center">
<Form onSubmit={Add} className='bg-success text-white bg-
opacity-50 border border-dark rounded w-50 shadow-lg p-3 mb-5 rounded'>
<Form.Group className="field mt-4 mb-4">
<div className="Formulario_usuario container pl-2 ">
<Row>
<Form.Label className=" d-flex justify-
content-center" style={{fontSize: 20}}>Imagen Actividad</Form.Label>
<Form.Control className="mb-3" type="file"
id="input-files" onChange={PreviewImg} />
</Row>
<Row>
<div className="container pl-2 d-flex justify-
content-center">
{previewImages && <img src={previewImages}
style={{maxWidth: "200px"}}/>}
</div>
</Row>
<div className= "d-flex justify-content-center
align-items-center mt-3">
<Button variant="success" type="submit" className=
"border-dark w-100">
Añadir Imagen
</Button>
</div>
</div>
</Form.Group>
</Form>
</div>
</div>
</div>
)
}

export default AddImage;

React mostrar imagen:


import React, { useState, useEffect } from 'react'
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css';
import Col from 'react-bootstrap/esm/Col';
import Row from 'react-bootstrap/esm/Row';
import Card from 'react-bootstrap/esm/Card';
import { Buffer } from 'buffer';

const ShowImage = () => {


const [listImages, setListImages] = useState([]);

const GetImg = async (e) => {


e.preventDefault();
const listIMG = await axios.post("/getImg");
console.log("Imagenes:");
console.log(listIMG.data);
setListImages(listIMG.data);
};

useEffect(() => {
console.log("useEffects ok");
GetImg(new Event(''));

}, []);

return (
<div style={{
backgroundImage:
`url("https://sirc.ca/wp-content/uploads/2020/03/AdobeStock_298604606-
scaled.jpeg")`,
backgroundSize: "cover"
}}>
<div className='bg-success bg-opacity-25'>
<div className= "form-container vh-100 d-flex justify-content-
center align-items-center">
{<Row xs={1} md={4} className="g-4 mt-1 mb-5">
{listImages.map((image) => (//Es un for each no se asusten
<Col key={image.idImgOrg}>
<Card className={`box-shadow`}
key={image.idImgOrg}>
<Card.Img
src={`data:image/jpeg;base64,$
{Buffer.from(image.ImgOrg).toString('base64')}`}
alt={image.name}
/>
</Card>
</Col>
))}
</Row>}
</div>
</div>
</div>
)
}

export default ShowImage;

Configuración index server:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true, parameterLimit:100000, limit: "500mb" //the two body parsers
are so that you can accept form requests from an html
}));

IMPORTANTE: Instalar lo siguiente:


-En cliente:
npm install buffer
En server:
npm install multer

You might also like