Unable to display image on HTML page in Sails JS

In my current project, I am utilizing Sails Js and Mongo DB for development. When a user uploads an image and content for a blog post, I store it in the images folder and save the file destination along with the content to MongoDB. My goal is to display both the content and the image on my HTML page using the file destination. While the content displays correctly, I am facing an issue with displaying the image. Here is a snippet of the controller code:

savepost:function(req,res){
        var uploadFile=req.file("image")
        uploadFile.upload({maxBytes:1000000,dirname:'../../assets/images'}, function onUploadComplete(err, files) {
            // Files will be uploaded to ./assets/images
            // Access it via localhost:1337/images/file-name
            if (err) return res.serverError(err);
            filename=files[0].fd;
        var content=req.body.content;
        var title=req.body.title;
       Cyberblog.create({title:title,content:content,date:date,filename:filename,}).exec(function(err){
            if(err){
              console.log(err);
              message="content not saved";
                console.log(message)
              res.redirect('/newpost');
            }
            else{
     var start=filename.lastIndexOf('\\');
     fd="images/"+filename.substring(start+1)
      post={
          title:title,
          content:content,
          fd:fd,
      }
      res.view('pages/blog/blog',{post:post})
    console.log("successfully saved")}
    }); }); },

Below is a snippet from the HTML file where I attempt to display the post:

<div class="container">
      <div class="row align-items-stretch retro-layout-2">
        <div class="col-md-4">
          <a href="single.html" class="h-entry mb-30 v-height gradient" style="background-image:url(<%= post.fd %>);">
            <div class="text">
              <h2><%= post.title %></h2>
            </div>
          </a>
        </div>
      </div>

I'm uncertain if my usage of <%= post.fd %> in the HTML file is correct. Any assistance or advice would be greatly appreciated.

Answer №1

After running sails lift with Grunt tasks, the /assets/images directory is moved to .tmp/public/images.

To ensure your file is stored in the correct directory, check the uploadedFile.fd value. The public directory is located at .tmp/public, so for images to be accessed at

localhost:1337/images/my-image.png
, they should be placed in .tmp/public/images/my-image.png.

To access the file via URL in the controller, you can use the relative path like this:

const url = require('url')
post.imageUrl = url.resolve(sails.config.custom.baseUrl, post.fd)

In the view, utilize the imageUrl value to display the image:

<a href="single.html" class="h-entry mb-30 v-height gradient" style="background-image:url(<%= post.imageUrl %>);">

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

I'm having trouble importing the slider component from Material-UI

import Slider from '@material-ui/lab/Slider'; Returns an error during the build process. ERROR in ./src/components/StepSlider/StepSlider-view.jsx Module not found: Error: Can't resolve '@material-ui/lab/Slider' in 'D:\G ...

Having difficulty transferring navigation props between screens using react-navigation

Within my ContactList component, I have utilized a map to render various items. Each item includes a thumbnail and the desired functionality is that upon clicking on the thumbnail, the user should be directed to a new screen referred to as UserDetailsScree ...

Tips for inserting a Vue.js variable into a window.open event

Within this snippet of code: <tr v-for="person, index in People" :key='index'> <td> <button type="button" onclick="window.open('/details/'+person.id,'_blank')"> details</butto ...

Is it possible for me to include additional fields in a vuetify calendar event?

Is there a method to incorporate additional fields, such as a description, in addition to the name and start/end time for an event on the v-calendar's day view? ...

A guide to deactivating the Material UI Link API element

Previously, I relied on Material UI's Button component with a disable property that allowed the button to be disabled based on a boolean value. However, I now want to use the Material UI Link component, which resembles a text link but functions like a ...

Executing multiple parallel async.waterfall functions in Node.js

In my current scenario, I find myself in a situation where I have four Async.waterfall functions that need to be executed simultaneously. Is it viable to accomplish this using Async.parallel or should I look into utilizing a different function? ...

Tips for utilizing variables as the initial value of a JSON Object

Here is a JSON configuration example: { "Users" : { "182723618273612" : 15, "AddedUser" : 1 } } I have generated this field using a JavaScript function, but now I want to change the name of "AddedUser" ...

What is the best way to show input choices once an option has been chosen from the 'select class' dropdown menu?

When it comes to displaying different options based on user selection, the following HTML code is what I've been using: <select class="form-control input-lg" style="text-align:center"> <option value="type">-- Select a Type --</opti ...

Guide for positioning all navbar items except one to the left, beginning at the left edge, utilizing a set minimum and maximum width, while moving the final item to the right edge

Is there a way to align all items in a navbar except for one to the left, with a fixed combined minimum and maximum width of 300px-400px, while sending the last item to the right margin? I want the final result to resemble this: https://i.stack.imgur.com ...

The range filter is exclusive to the initial controller

My range filter (see code below) is only working on my first controller. I have added the same filter to other controllers in the app.js and HTML, but it's not functioning for some reason. I checked the console for errors, but there are none. Here i ...

Creating an alert pop-up that displays text based on the prompt input type: A step-by-step guide

I'm a new to Javascript and I'm trying out some basic scripts. My objective is to display a prompt message (1.) asking for a name, then show an alert (2.) based on the input from the prompt. If the input is a valid name (a string), then the alert ...

"X-Requested-With" header not being included in XMLHttpRequest request

After successfully using jQuery.ajax() to make an ajax call to an MVC action, I decided to switch to using the XMLHttpRequest along with the HTML5 File API due to some forms containing file controls. However, since making this change, the MVC action no lon ...

Is it possible to have nullable foreign keys using objectionjs/knex?

It seems like I'm facing a simple issue, but I can't quite figure out what mistake I'm making here. I have a table that displays all the different states: static get jsonSchema() { return { type: 'object', propert ...

ngRepeat does not iterate through an array

Presented below is an object: { "_id" : ObjectId("5454e173cf8472d44e7df161"), "questionType" : 0, "question" : "question1", "answers" : [ { "content" : "answer1" }, { "is_true" : "true", ...

Developing desktop applications using C# scripting

I currently have a C# desktop program that is able to work with new C# plugins. My goal is to modify the existing C# application to allow for scripts to be used as plugins. These scripts could be in JavaScript, Windows Script Host (WSh), or any other form ...

Angular and Node.js Integration: Compiling Files into a Single File

I have a question, is it possible to include multiple require js files in one file? If so, how can I create objects from them? Calling 'new AllPages.OnePage()' doesn't seem to work. To provide some context, I'm looking for something sim ...

The inner HTML functionality in Angular 2 seems to be malfunctioning when dealing with HTML tags

I am facing an issue with an array that includes displayName with HTML tags: this.topicsList = [ {id: "173", name: "Discussion1", displayName: "Discussion1", status: 1}, {id: "174", name: "discussion123", displayName: "discussion123", status: 1}, {id: "19 ...

Error in Rails due to a Javascript issue

My journey with learning Javascript started by following an easy game tutorial on RoR. I encountered an error in index.html.erb file which led me to a helpful video tutorial here. <script> var ctx, canvas; var data; window.onload = fun ...

Save the function as a local variable and preserve the reference to the current object

In the prototype of my Car object, I have a function that looks like this: Car.prototype.drive = function() { this.currentSpeed = this.speed; } I find myself needing to call this drive function frequently within another function of the Car prototype. ...

Issue Encountered during Git Bash Installation of React-Scripts: "UNRECOGNIZED ERROR: unknowingly, scanning directory 'E:... ode_modules@babel.helper-annotate-as-pure.DELETE'"

ERROR: An unknown error occurred while trying to scan directory 'E:\Sorted\Capstone\WOO-WOO.net\WOO-WOO.net\project\FrontEnd\frontendapp\node_modules\@babel\.helper-annotate-as-pure.DELETE' Encou ...