troubles displaying images that have been uploaded in sails

  function addFlight(req, res) {
    Airline.create({
      name: req.param('name'),
      email: req.param('email'),
      office: req.param('office'),
      phone: req.param('phone')
    }, function airlineCreated(err, newAirline) {
      if (err) {
        console.log('Error: ' + err);
        return res.negotiate(err);
      } else {
        console.log('uploading file');
        req.file('file').upload({
          maxBytes: 10000000,
          dirname: '../../assets/images/'
        }, function whenDone(err, uploadedFiles) {
          if (err) {
            console.log(err);
            return res.negotiate(err);
          }

          if (uploadedFiles.length === 0) {
            console.log("No file");
            return res.badRequest('No file was uploaded');
          }

          Airline.update(newAirline.id, {
            logoUrl: require('util').format('%s/airline/logo/%s', sails.getBaseUrl(), newAirline.id),
            logoFd: uploadedFiles[0].fd
          }).exec(function (err) {
            if (err) {
              return res.negotiate(err);
              console.log(err);
            }
            return res.ok();
          });

        });

      }

    });

  }

I am currently learning the Sails framework and I encountered an issue with uploading and retrieving images. I followed the documentation and managed to get the uploading to work, as shown in the code above. Following that, here is the JSON format of my data after an image is uploaded.

 {
    "name": "imager",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef86af82c18c8082">[email protected]</a>",
    "office": "img",
    "phone": "24232",
    "createdAt": "2016-04-04T09:06:35.404Z",
    "updatedAt": "2016-04-04T09:06:35.438Z",
    "id": 11,
    "logoUrl": "http://localhost:1337/airline/logo/11",
    "logoFd": "/Users/musaddiq/Desktop/Other proples companies/AirportAngular/airport/assets/images/6bd339f5-bc72-458c-b04c-6670bc1b59a5.jpg"
  }

I have a list of individuals with images and a table view where I want to display all users with their logos. Below is the table view code. I am unsure how to proceed, as referencing the Sails documentation has not resolved my issue.

<div style="padding-top: 180px;" ng-app="airlineMod" ng-controller="airlineCtrl" class="container">
  <div ng-init="airlineList()">

    <table class="table table-responsive table-hover" ng-show="airlines.length">
      <thead>
       <tr>
         <td>
           Logo
         </td>
         <td>
          Name
         </td>
         <td>
           Office
         </td>
         <td>
          Email
        </td>
         <td>
          Phone Number
        </td>
       </tr>
      </thead>
      <tbody ng-repeat="airline in airlines">
          <tr>
            <td>
             <img ng-src="{{airline.logoUrl}}" class="img-responsive img-circle" width="50" height="50">
            </td>
            <td>
              {{airline.name}}
            </td>
            <td>
              {{airline.office}}
            </td>
            <td>
              {{airline.email}}
            </td>
            <td>
              {{airline.phone}}
            </td>
          </tr>
      </tbody>
    </table>

  </div>
</div>

Here is the code I attempted to use to retrieve the images:

 getAllFlights: function (req, res) {
    Airline.find({}, function found(err, airlines) {
      if (err) {
        return res.negotiate(err);
      }

      console.log("Airlines found");

      var SkipperDisk = require('skipper-disk');
      var fileAdapter = SkipperDisk();

      _.each(airlines, function (airline) {
        fileAdapter.read(airline.logoFd)
          .on('error', function (err) {
            return res.serverError(err);
          })
          .pipe(res);
      });

      return res.send(airlines);
    });
  }

However, I keep encountering the error "fs.js:262 binding.open(pathModule._makeLong(path), TypeError: path must be a string".

Answer №1

  add:function (req, res)
  {
    Airline.create({
      name:req.param('name'),
      email:req.param('email'),
      office:req.param('office'),
      phone:req.param('phone')
    },
      function airlineCreated(err, newAirline)
    {
      if(err)
      {
        console.log('Error: '+err);
        return res.negotiate(err);
      }
      else
      {
        console.log('saving file with original name');
        req.file('file').upload({
            maxBytes: 10000000,
            dirname: '../../assets/images',
            saveAs : _saveAs
        },
          function whenDone(err, uploadedFiles)
          {
          if (err)
          {
            console.log(err);
            return res.negotiate(err);
          }

          // If no files were uploaded, respond with an error.
          if (uploadedFiles.length === 0)
          {
            console.log("No file");
            return res.badRequest('No file was uploaded');
          }

          Airline.update(newAirline.id,
            {

              logoUrl: require('util').format('%s/images/%s', sails.getBaseUrl(),uploadedFiles[0].filename)

          })
            .exec(function (err)
            {
              if (err)
              {
                return res.negotiate(err);
              }

              return res.ok();
            });

        });

        function _saveAs(file, cb)
        {
          var newName = file.filename;
          return cb(null, newName);
        }

      }

    });

  }

I adapted the file saving process to use the original filename instead of a generated one, allowing me to reference the logoUrl more easily on the frontend.

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

Refreshing the page to dynamically alter background and text hues

I'm currently dealing with a website that generates a random background color for a div every time it is refreshed. I have a code that successfully accomplishes this: var colorList = ['#FFFFFF', '#000000', '#298ACC', &ap ...

Undefined property error

router.post('/:token',(req,res)=>{ let language= req.query.language let name= req.query.name let param =[] if(req.path.length == 5){ param.push({ language: language },{ name: name }) ddp.personConnected(param, function(err, response) { i ...

Comparing Angular 2 with Angular.js, React.js, and Typescript

Hello there, I am a fresh-faced web developer looking to create a modest website for my personal use. However, my knowledge is limited when it comes to JavaScript and jQuery concepts. In order to expand my skills and build an enhanced website, I decided ...

Retrieve asynchronous JSON settings before loading the AngularJS submodule library

I am dealing with a distributed AngularJs library module that is utilized in various other AngularJs applications which are out of my control. In my research, I have discovered that it is possible to load JSON settings for an AngularJs application via an ...

Convert h264 video to GIF using Node.js

Currently, I'm utilizing the "pi-camera" library to successfully record video in a raw h264 format on my Raspberry Pi. However, I am encountering an issue with the node.js library "gifify" which keeps throwing the error "RangeError: Maximum call stack ...

Is there a way to include a file in the headers of a POST request and still have standard data in the request body?

Is it possible to attach a file to the header of an existing POST API that is used to send objects to the server? Can a request have multiple content-types? I attempted to use the ngFileUpload directive and provided my object to the data field of the Uplo ...

Pass PHP array to a JavaScript file using AJAX

Starting with a basic knowledge of PHP and AJAX, I was tasked with creating a form that prompts the user to choose between two car manufacturers. Upon selection, the form should display all models of the chosen make from a multidimensional array stored in ...

How to enable cross-origin resource sharing

While using $resource for making http calls, I encountered an issue with my backend application being deployed on a different port. When attempting to fetch data from the server using the request method(GET), my browser automatically attaches the request m ...

Swapping values between HTML tables and arrays with the power of JavaScript

I have a unique table structure that I need help with: https://i.sstatic.net/fr7oJ.png My current table has 2 rows and multiple columns, but I want to change it to have 2 columns and multiple rows like this: https://i.sstatic.net/uhkp9.png To create th ...

Creating a dynamic dropdown menu in Laravel 5.3 - A step-by-step guide

Here is my HTML code: <div class="form-group has-feedback{{ $errors->has('kdkotama') ? ' has-error' : '' }}"> <select class="form-control" name="kdkotama" id="kdkotama"> <option value="">---- ...

The hovering effect on the image link is causing the surrounding div to stretch too far

Whenever I hover over specific points below an image link wrapped in a div, it triggers the hovering effect for the CSS-created image link. Despite trying various solutions like overflow:hidden and display:inline-block, nothing seems to resolve this issue. ...

An elusive static image file goes unseen within the realm of node.js/express

I am encountering an issue with serving static files in Express on Node.js. When I request a .css file from the server, everything works fine. However, if I try to load an image such as a jpg or png, it just shows a blank white page without any error messa ...

Preventing pageup/pagedown in Vuetify slider: Tips and tricks

I am currently using Vuetify 2.6 and have integrated a v-slider into my project. Whenever the user interacts with this slider, it gains focus. However, I have assigned PageUp and PageDown keys to other functions on the page and would like them to continue ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...

Can I apply a universal babel configuration across all of my personal projects?

It becomes tedious to duplicate the same configuration file for each new project I start. ...

Bootstrap 4 modal experiencing issues with the form end tag functionality

Currently, I am facing an issue while attempting to incorporate a confirmation delete feature using a Bootstrap 4 modal in my Laravel project. The problem arises when the modal is opened, and the submit button fails to function. Upon inspecting the browser ...

Encountered an error while trying to run npm start

I set up a Vagrant virtual machine, installed Node.js (v 6.9.1), and NPM (v 4.0.0). After cloning a Node.js app using Git clone, I ran the npm install command in both the root folder and the app folder. However, when attempting to start the app with npm st ...

Retrieving Data with AngularJS: Making HTTP Calls and Handling Responses

I seem to be facing a bit of a hurdle in executing an HTTP GET request and retrieving the data properly in JavaScript. The goal is to attach this data to the global window variable, but I'm encountering some difficulty. Here is the code snippet for t ...

Issue with my lazyloading extension for Mootools

Seeking to create a plugin for sequential image downloads using MooTools. Assuming there are images with the img tag inside a div with the class imageswrapper. The goal is to download each image in order, one after the other until all images are loaded. ...

A step-by-step guide on implementing the bootstrap paginator library to paginate PHP echoed data

I'm currently working on a project that involves displaying data from a database in a table. To make the data paginated on the client side, I decided to use the bootstrap paginator library available at: Below is the code I'm using: In my header ...