Save image files as binary data within a Mongoose schema and then render the images in an HTML form

Utilizing Express, Node.js, and Mongodb to develop a webpage for uploading and displaying image files.

The binary of the image is stored in Mongodb using a schema.

Below is a snippet of code from index.js and db.js:

var Post = mongoose.Schema({
   image: {data: Buffer, contentType: String}
});

var post= new Post({ });
post.image.data=fs.readFileSync(req.file.path);
post.image.contentType='image/png';

Following the submission and search for a post within the mongo shell, here is part of the code relating to the image field:

"image: {"data:BinData(0,"iVBORw0KGgoAAAANSUhEUE.... (truncated)
rkJggg=="),
"contentType": "image/png"} 

It appears that the binary data of the image file is successfully saved in Mongodb,

However, the issue lies in displaying the image on the webpage using the binary data. How can the binary buffer data be converted to create an image tag?

<img src="data:{{image.contentType}};base64,{{image.data}}">

An attempt was made with the above code, resulting in an error:

Failed to load resource: net::ERR_INVALID_URL

If you have any insights on how to resolve this issue, your assistance would be greatly appreciated. Thank you!

Answer №1

To begin, the first step is to encode buffer data into base64 format. This conversion can be done either on the back-end or front-end without any issues. Simply utilize

yourBufferData.toString('base64')
for this purpose.

Alternatively, I recommend a different approach for image storage instead of storing binary data directly. If you are working with nodejs, consider creating an image file in a designated repository using the fs.writeFile method. Subsequently, save the file path to the corresponding record in the database. Then, simply insert the file path into

ng-src="file path which you saved"
. The following code snippet illustrates how this process can be implemented:

var path = 'upload/profiles/' +req.body.userId + '_profile.jpg';
      fs.writeFile(path, base64data, function(err) {
        if (err) return next(err);
        User.findByIdAndUpdate({
          _id: req.body.userId
        }, {
          $set: {
            profileImg: 'upload/profiles/' +req.body.userId + '_profile.jpg'
          }
        }, function(err, user) {
          if (err) return next(err);
          return res.send(user);
        });
      });

  <img ng-src="savedpath">

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

A guide on utilizing AngularJS to extract data from a webpage

I'm attempting to transfer the information from a specific page on my website and paste it into a file. I know how to post a sample text stored in a variable from Angular and save it in a file in the backend using Node Express, so writing a file isn&a ...

Implement static backgrounds on images within an Angular application

I am new to using Angular 7 and I have hit a roadblock. I need help understanding how to resize images so that either the height is 270 and the width is less than 470, or the width is 470 and the height is less than 270. Once resized, I want to place these ...

Could it be an issue with Jquery? Maybe it's related to AJAX reload, or possibly just a case

Utilizing the following Jquery : $('#resultstable').on('click', 'tbody tr', function() { alert("helloworld") $('#resultstable tr.Selected').removeClass('Selected'); $(this).addClass('Selected'); ...

Returning a set of indexes for two elements in an array that combine to equal a specified target sum

For my current project, I've been tasked with writing a function that accepts an array of numbers along with a target number. The goal is to identify two numbers in the array that can be added together to reach the target value, and then return the i ...

Introducing a pause in the function while rendering objects

After inserting setInterval into the code, it is causing all lasers to be delayed by one second. I am looking to have them fired in this order: - initially fire laser1 and laser2. - then take a 1-second break before firing another set of lasers, a ...

Alert: Unauthorized hook call and Exception: Cannot access properties of null (reading 'useState')

I am currently working on a project using ASP.NET Core with React. To bundle my code, I have opted to use Webpack 5. Within the index.jsx file, I have the following code: import { useState } from "react"; function App() { const [value, setV ...

How to achieve a seamless iframe effect using CSS

With the introduction of new HTML5 iframe attributes, there are now more options available. One such attribute is the seamless attribute, which has the ability to: Create an iframe that appears to be seamlessly integrated into the containing document. ...

Strategies for Managing Output Event Prioritization in Angular Using RxJs Based on Trigger Sequence

Within my Angular Application, there is a widget with two event outputs originating from a third-party library. Unfortunately, I am unable to modify its behavior. <myWidget (onAlwaysEvent)="onAlwaysEvent($event)" (onSometimesEvent)="onSometimesEven ...

Run a JavaScript function once the AJAX content has been successfully added to the element

I have a JavaScript AJAX function that retrieves content and adds it to an HTML element named content_holder. After the content is updated with the AJAX request, I want to trigger a function. I've attempted to include a <script> tag within the a ...

Learn the process of transferring data from a page to a layout in NUXT

I am in the process of creating a basic website. The goal is to dynamically change the Navbar elements based on the data set in the navLayout within the page template. My plan is to pass this data to the layout and then utilize props to transmit it to the ...

AngularJS Treeview - Rearranging tree nodes

My journey with Angular is just beginning, and I managed to create a treeview following this example: jsfiddle.net/eu81273/8LWUc/18/ The data structure I've adopted looks like this: treeview1 = [ { roleName: "User ...

The Next.js build version encounters an issue with 'auth' property being undefined and causes a failure

Our team has been happily working on a Next.js based website for the past few months. Everything was running smoothly without any major issues until yesterday when we encountered an error on the production version while using router.push: Cannot read prope ...

What is the best way to refresh resources after the state of the Admin component has been updated?

My approach to dynamically obtaining resources through a function was working well until I encountered an issue with changing screen sizes. I believed that by adding a state called "screenSize" in the admin component and updating it upon resize, I would ...

What is the best way to expand a div in a downward direction exclusively?

My task involves a parent div containing a centered child div. My goal is to have the child div grow downwards only upon clicking it, not in both directions. Initial state of the two divs: https://i.sstatic.net/cWYyV.png Outcome after clicking on div 2: ...

Setting the unique property for a Schema in mongoose: A guide

In my NodeJS application, I rely on Mongoose to interact with MongoDB. However, I encountered an issue when trying to set a field in my Schema as unique. Despite following the guidelines provided in the official documentation, I was unable to achieve thi ...

Is it possible to efficiently utilize Map/Set in TypeScript/JavaScript when working with objects?

I'm currently transitioning from Java to TypeScript and I've encountered an issue with working with objects in hashmaps and hashsets. In Java, I would simply override the hashCode method to easily manipulate these data structures. Is there a simi ...

"Exploring the Relationship between MongoDb and C#: Choosing Between Embedded or Reference Document

When working with MongoDB, is it better to use Document References or Embedded documents for linking entities? This question arises in the context of the following code: class ObjectType1 { ObjectId ID; ObjectType2 Type2Element; } class ObjectType2 { Obj ...

JavaScript logic for playing the hangman game

I am working on creating a hangman game and I need some guidance on developing the logic. I am new to programming, so I would like to keep it simple by using basic syntax. One thing I'm trying to figure out is how to display dashes (-) that represent ...

Load External HTML content into webpage along with executing JavaScript code and triggering JS functions upon loading

I'm in search of a super lightweight solution that can effectively load an external HTML file into a page using only vanilla JavaScript. The external file contains HTML, CSS, and JS. Essentially, I want to create a concise JS snippet that loads a butt ...

"The click event doesn't seem to be functioning properly on HTML content loaded dynamically through JavaScript

I have set up a dynamic page that initially loads 10 elements. As the user scrolls down, I use JavaScript to append more elements to the page via AJAX. Additionally, when a tag is clicked, some JavaScript functionality is triggered. Specifically, I am uti ...