View the picture in a web browser

Currently, I am faced with the challenge of displaying an image that is stored in an MSSQL database created by another person.

The column was originally of type IMAGE, but I converted it to varbinary(MAX) using Sequelize. Although I lost some data during testing, it was necessary for the process.

After reinserting the image, I attempted to display it on my fotos.handlebars file.

Unfortunately, all I got were a string of characters instead of the actual image:

printResult.png

I'm seeking advice on how to rectify this issue and successfully display the image.

This is my code snippet:

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())


//Routes
app.use('/fotos', (req, res)=>{
   //res.send('test route')
   
     Fotos.findAll().then((fotos)=>{
        res.render('fotos', {fotos: fotos})
    }).catch((error)=>{
        res.send(error)
    })
    
})


app.listen(8081, ()=>{
    console.log('Server is running')
})

Answer №1

Have you attempted to utilize your blob as the src attribute of an image? In the code, you are placing it inside an h2 tag which is intended for text, causing it to display the blob text as gibberish due to its binary nature.

const urlCreator = window.URL || window.webkitURL;
const imageUrl = urlCreator.createObjectURL(dataValues.Foto);
const image = new Image();
image.addEventListener("load", () => {
  // Append the image to your webpage
}
image.src = imageUrl;

You should try something similar to this approach

EDIT: You can use Handlebars helpers to transform your blob into a URL

Handlebars.registerHelper('blobToUrl', function(blob) {
   var urlCreator = window.URL || window.webkitULR;
   var imageUrl = urlCreator.createObjectURL(blob);
   return imageUrl;
 });

Then implement the following

<h1>Photos:</h1>

{{#each photos}}

    <img src="{{blobToUrl dataValues.Foto}}"></img>
    <hr>

{{/each}}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of Node.js middleware is not functioning correctly

My module contains Routes, and I want to verify access before allowing users to proceed. Within the Routes module, there are two routes and two access-check functions that I want to use as middlewares: const checkUser = (req, res, next) => { if (!us ...

The issue with the <Button> component not properly linking in next.js

Having trouble with a button wrapped inside a custom Navbar component. The code snippet in question is: <NavBtn> <Link href="/contact" passHref> <Button> Contact Me </Button> </Link> & ...

The error message "exec format error" was caused by the process run by the user on line 190 of standard_init_linux.go. The command '/bin/sh -c npm install' resulted in a non-zero exit code of 1

Being new to docker, I decided to dive into learning by following the official nodejs docker instructions. However, I encountered an error while trying to execute the same command repeatedly. My attempt at creating docker images on a Raspberry Pi to use a ...

Experience the dynamic bouncing marker feature in Next.js React-Leaflet with the powerful tool Leaflet.SmoothMarkerB

I'm a beginner in front-end development and I'm attempting to create a bouncing marker in React-leaflet using the leaflet.smooth_marker_bouncing plugin version 1.3.0 available at this link. Unfortunately, I couldn't find enough documentation ...

Refreshing the parent page in Oracle Apex upon closing the child window.When the child window

I have created an interactive report with a form where the interactive report is on page 2 as the parent page and the form page is on page 3 as the child page. In the parent page, I have written JavaScript to open a modal window (form page - page 3) using ...

Vuetify alters the text color of the <vs-button> element

Outline of the Issue Upon installing vuetify, the text color of my <vs-button> has changed from white to black. Despite trying to adjust the color in the vuetify theme, I am unable to change it back. I have also created a custom filter rule using po ...

What sets apart app.use(express.static(__dirname + '/public')) from app.use(express.static('public'))?

I am curious to know if the following two code snippets are equivalent. (1) app.use(express.static(__dirname + "/public")); (2) app.use(express.static("public")); I believe that (2) should be sufficient for serving the public folder fr ...

Why is jQuery not defined in Browserify?

Dealing with this manually is becoming quite a hassle! I imported bootstrap dropdown.js and at the end of the function, there's }($); Within my shim, I specified jquery as a dependency 'bootstrap': { "exports": 'bootstrap', ...

Struggling to display my array data retrieved from the database on my Angular 5 page

I hope everyone is doing well. I am currently facing a problem with retrieving data from Firebase. I have an array within an array and I want to display it in my view, but I am encountering difficulties. Let me share my code and explain what I am trying to ...

Tips for preventing breaks in typography

I have implemented a material ui Typography component, but it's causing a line break even though there is enough space. Here is the code snippet: <Box flexDirection="row"> <Typography> Gender: <RadioGroup row ...

Creating a Button with Icon and Text in TypeScript: A step-by-step guide

I attempted to create a button with both text and an icon. Initially, I tried doing it in HTML. <button> <img src="img/favicon.png" alt="Image" width="30px" height="30px" > Button Text ...

Does TypeGraphQl have the capability to automatically format SQL queries?

I am utilizing TypeORM in conjunction with TypeGraphQL. I am curious about the SQL query result that TypeGraphQL provides. For instance, if I have a User Table with numerous columns and a simple resolver like this: @Resolver() class UserResolver { @Q ...

When the user clicks, the template data should be displayed on the current page

I need help with rendering data from a template on the same HTML page. I want to hide the data when the back button is clicked and show it when the view button is clicked. Here is my code: <h2>Saved Deals</h2> <p>This includes deals wh ...

Making Node.js Wait Until a Function Completes its Execution

Currently, I am using a for-loop in Node.js to run the x() function from the xray package. This function scrapes data from webpages and then writes that data to files. The program works well when scraping around 100 pages, but I need it to handle around 10 ...

Windows encountering a Node npm error while searching for tools version

Currently, I am encountering an issue while trying to use node on my Windows 8.1 operating system. The problem arises when I attempt to install npm packages using 'npm install package.json'. It all started when I began using Redis, but I'm n ...

The login attempt is unsuccessful with Bcrypt

I've come across this issue multiple times, but haven't been able to find a solution either here or on GitHub. My login handler compares hashed passwords from the database to the user input during login. However, bcrypt.compare almost always retu ...

"The power of Node JS in handling JSON data and gracefully

I'm having trouble extracting a specific part of a JSON object in Node JS. When I print the response body, the entire object is displayed correctly. However, when I try to access object.subsonic-response, it returns NaN. I've spent a lot of time ...

Need help with creating a new instance in AngularJS? Unfortunately, the save method in CRUD is not getting the job done

Whenever I attempt to create a new task, nothing seems to happen and no request is being sent. What could be causing this issue? How can I go about troubleshooting it? Take a look at how it appears here Check out the $scope.add function below: var app ...

The express error middleware is failing to properly handle errors that are being thrown from the promise's

When I throw an Error, express will render it nicely using the connected errorHandler middleware. exports.list = function(req, res){ throw new Error('asdf'); res.send("We don't reach this point because the Error is thrown synchronously" ...

Is there a more efficient method to execute this AJAX request?

$('#request_song').autocomplete({ serviceUrl: '<%= ajax_path("trackName") %>', minChars:1, width: 300, delimiter: /(,|;)\s*/, deferRequestBy: 0, //miliseconds params: { artists: 'Yes' }, onSelect: functi ...