Sending data using Sails Js POST method

I am facing an issue with my html form that sends a POST request to /upload/upld in my sails app. The goal is to upload a photo and include the location where the photo was taken as parameters. The upload controller should save the file in a directory named after the location parameter.

      <form method="post" action="/upload/upld" enctype="multipart/form-data">
        <span class="btn btn-default btn-file wow bounceIn top-buffer">
          Browse <input type="file" name="photo">
          <input type="hidden" name="location" value="istana" />
        </span>
          <input type="submit" class="btn btn-primary wow bounceIn top-buffer">
      </form>

However, there seems to be an issue with this code. Whenever I try to upload a single file, the upld method appears to run twice based on the console output. This is confusing and I'm unsure why it's happening.

{ location: 'istana', id: undefined }
istana
{ id: undefined }
undefined

Here is what my upload controller currently looks like:

    upld: function (req, res) {
            var params = req.params.all();
            console.log(params);
            var this_location = params.location;
            console.log(this_location);
            req.file('photo').upload({ dirname:require('path').join('./',this_location)},function (err, files) {
                    if (err){
                            return res.serverError(err);
                    }
                    return res.view('homepage',{

                                    message: files.length + ' file(s) uploaded successfully!',
                                    files: files
                            }
                    );
            });
    }

Answer №1

After some investigation, I discovered that the issue stemmed from my form structure. The utilization of Skipper by Sails to manage multipart/form-data required me to rearrange the positioning of the file input element after the hidden text field.

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

Utilize Angular to organize data in a single-dimensional array

In my project, I am using Angular and Bootstrap to create a dynamic data grid where users can edit the data. The dataset consists of an array of objects, with each object containing a non-unique group property to categorize records. For example: [ { ...

Despite my attempts to extract the image from the html data table and showcase it in a div, the image remains elusive and refuses to appear

I am currently able to extract data from an HTML data table and set it into a textbox. However, I am facing an issue when trying to retrieve an image from the HTML data table and display it in a div element. Unfortunately, the image is not showing up. Any ...

Efficient methods to reach the desired result using Selenium WebDriver promises

After working on a piece of code that utilizes Selenium WebDriver to retrieve the text of an element, I am wondering if there is a more concise way to accomplish this task? async function getText(driver, locator) { return await (await driver.findEleme ...

Issue with firebase.auth() method not triggering onAuthStateChanged after user login/logout操作

My code looks like this: var config = { apiKey: "xxxxx", authDomain: "xxxxx", databaseURL: "xxxxx", projectId: "xxxxx", storageBucket: "xxxxx", messagingSenderId: "xxxxx" }; firebase.initializeApp(config); $("#l ...

Extract the value of an HTML tag and store it in a PHP variable

I have successfully implemented JavaScript code to dynamically update the value of an input tag in my popup. However, when I try to echo out this updated value using a PHP variable within the same popup, it doesn't seem to work as expected. Despite un ...

What is the best way to locate elements with the term "download" in them using Selenium's x-path feature?

I'm currently utilizing Selenium for web scraping purposes and I am in need of a way to identify all clickable elements that contain the word "download" (regardless of capitalization) within their link text, button text, element ID, element class, or ...

Puppeteer gathers data on page loading - including a comprehensive list of files loaded and their respective sizes

Is it feasible to compile a complete list of all files loaded on a webpage using Google's Puppeteer? This would include scripts, styles (excluding inline), images, videos, and audio, along with their respective sizes. If Puppeteer cannot provide this ...

Tips for troubleshooting React issue (TypeError: Cannot read property 'showModel' of null)

Learn how to set the attribute showModel and give it a value of false: Main.js import React from 'react' import 'bootstrap/dist/css/bootstrap.min.css'; import Form from 'react-bootstrap/Form' import Button from 'react-b ...

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

Utilizing Three.js for onWindowResize event parameterization

As I delve into the world of JavaScript coding and experiment with Three.js, I've come across a function that dynamically scales my scene based on the size of the browser window: function onWindowResize() { camera.aspect = window.innerWidth / wi ...

Can you explain what vercel is trying to convey with the message "Invalid request: should NOT have additional property `route`. Please remove it"?

I'm unsure about this I'm not entirely sure what that signifies. I've checked to see if it pertains to my route folder or something else, but I'm still confused. Can someone please assist me in understanding this? ChatGPT hasn't p ...

Retrieve the observable value and store it in a variable within my Angular 13 component

Incorporating Angular 13, my service contains the following observable: private _user = new BehaviorSubject<ApplicationUser | null>(null); user$ = this._user.asObservable(); The ApplicationUser model is defined as: export interface ...

An error occurs when trying to load data into a grid upon clicking, resulting in an Uncaught TypeError: Unable to access properties of undefined (specifically 'dataState')

I have implemented a grid in React using a specific library, and I want to populate the grid with data fetched from an API call when the user clicks on a button labeled Fetch Products. However, I encounter an error during debugging: Uncaught (in promise) T ...

What is the best way to combine two arrays of objects with varying values for the same key, and add a new object to the mix?

I have two arrays: arr1 = [ { "OwnershipNumber": 0, "ID": null, "Name": "Contractor LLC", "ContrEmployeeTypeId": 0, "ContactEmail": "", "ContactPhone": "", "VeteranEmployeeMilitaryAffiliation": "", "SocialSecurityNumber": ...

Addressing component validation conflicts in Vuelidate on VUE 3

I am currently experiencing an issue with VUE 3 Vuelidate. In my project, I have 2 components that each use Vuelidate for validation (specifically a list with CRUD functionality implemented using modals). However, when I navigate from one component to anot ...

What is the purpose of mapping through Object.keys(this) and accessing each property using this[key]?

After reviewing this method, I can't help but wonder why it uses Object.keys(this).map(key => (this as any)[key]). Is there any reason why Object.keys(this).indexOf(type) !== -1 wouldn't work just as well? /** * Checks if validation type is ...

Modifying the background color using highcharts.js

I am attempting to customize the background colors of a highcharts scatter plot. While I can easily change the color of a specific section using the code provided, my goal is to apply multiple colors to different ranges within the same plot. Specifically, ...

When touch-triggered on IOS, HTML5 Web SQL Transactions were smoothly bypassed without any errors

I'm encountering issues with database transactions on IOS devices. When the user does not interact with the phone, everything functions as expected. However, if the user taps, scrolls, or touches the screen, some transactions bypass the actual transac ...

Utilizing the Java Script SDK for Facebook API to Publish Actions

I've been encountering difficulties with the Facebook API. I have created an app, an object, and an action, and I'm trying to test publishing in my stream (I understand that public publishing needs authorization from Facebook, but as an administr ...

How can I retrieve information from an HTML or JavaScript object?

Imagine a scenario where you have an HTML table consisting of 5,000 rows and 50 columns, all generated from a JavaScript object. Now, suppose you want to send 50 checked rows (checkbox) from the client to the server using HTTP in JSON format. The question ...