Reputation: 3
So, I am trying to present an image that is saved in MSSQL in a database that is already made by someone else.
Originally the column is of the IMAGE type, using Sequelize I converted to varbinary(MAX). Yes, I lost the data but it was for testing only
Then I inserted the image again and tried to show it on my fotos.handlebars.
And that was the result:
Is there any way to make the image appear instead of these characters?
My code:
Model Fotos.JS:
const db = require('./db')
const Fotos = db.sequelize.define('Fotos', {
COD_PESSOA:{
type: db.Sequelize.INTEGER
},
Sequencia:{
type: db.Sequelize.INTEGER
},
Foto:{
type: db.Sequelize.BLOB
},
Padrao:{
type: db.Sequelize.INTEGER
}
}, {
timestamps: false
})
module.exports = Fotos
//Fotos.sync({force: true})
fotos.handlebars:
<h1>Fotos:</h1>
{{#each fotos}}
<h2>{{dataValues.Foto}}</h2>
<hr>
{{/each}}
app.js:
const express = require('express')
const app = express()
const handlebars = require('express-handlebars')
const bodyParser = require('body-parser')
const Fotos = require('./models/Fotos')
//template engine
app.engine('handlebars', handlebars({defaultLayout: 'main'}))
app.set('view engine', 'handlebars')
//body-parser
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
//Rotas
app.use('/fotos', (req, res)=>{
//res.send('teste rota')
Fotos.findAll().then((fotos)=>{
res.render('fotos', {fotos: fotos})
}).catch((erro)=>{
res.send(erro)
})
})
app.listen(8081, ()=>{
console.log('Servidor Rodando')
})
Upvotes: 0
Views: 290
Reputation: 97
Have you tried to put your blob as src
of an image? In the code your putting it inside of an h2
which is text, so it will print the blob text, because it's binary it looks like gibberish.
const urlCreator = window.URL || window.webkitURL;
const imageUrl = urlCreator.createObjectURL(dataValues.Foto);
const image = new Image();
image.addEventListener("onload", () => {
//append the image in your body page
}
image.src = imageUrl;
try something like that
EDIT: You can use the handlebars helpers to transform your blob to URL
Handlebars.registerHelper('blobToUrl', function(blob) {
var urlCreator = window.URL || window.webkitULR;
var imageUrl = urlCreator.createObjectURL(blob);
return imageUrl;
});
then do this
<h1>Fotos:</h1>
{{#each fotos}}
<img src="{{blobToUrl dataValues.Foto}}"></img>
<hr>
{{/each}}
Upvotes: 1