What is the best way to pass the value of a selected option to an express server

<label for="exampleFormControlSelect1">
  <strong>Please Select the Number of PDFs to Merge:</strong>
</label>
<select class="form-control" id="exampleFormControlSelect1">
  <option name="number">1</option>
  <option name="number">2</option>
  <option name="number">3</option>
  <option name="number">4</option>
  <option name="number">5</option>
</select>
app.post("/merge", upload.array("pdfs", 2), async (req, res, next) => {
  console.log(req.files);
  let d = await mergePdfs(
    path.join(__dirname, req.files[0].path),
    path.join(__dirname, req.files[1].path)
  );
});

I have hard-coded the option for merging 2 PDFs but the user can select any number.

Answer №1

  1. Modify the Multer middleware to allow for unlimited file uploads.

    upload.array("pdfs")
    
  2. Ensure that your <select> element has a designated name attribute to be included in the request payload.

    <select
      required
      name="limit"
      class="form-control"
      id="exampleFormControlSelect1"
    >
    
  3. Verify the length of req.files against req.body.limit and handle any discrepancies by extracting the file paths and passing them to mergePdfs()

    app.post("/merge", upload.array("pdfs"), async (req, res, next) => {
      const { limit } = req.body;
      if (req.files.length !== limit) {
        return res.status(400).send(
          `Expected ${limit} file(s), received ${req.files.length}`
        );
      }
    
      try {
        const result = await mergePdfs(
          ...req.files.map(({ path: filePath }) => filePath)
        );
    
        // Handle the merged PDF document here
      } catch (err) {
        next(err);
      }
    

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

Unraveling Vue Async Components - Harnessing the power of emitted events to resolve

I am looking to create a Vue async component that stays in a loading state until a custom event is triggered. This means it will render a specified loading component until the event occurs. Here's an example of how I want it to work: const AsyncComp ...

What is the best way to extract data from a textarea HTML tag and store it in an array before iterating through it?

I have a project in progress where I am developing a webpage that will collect links from users and open each link in a new tab. I am using the <textarea> tag in HTML along with a submit button for link collection. Users are instructed to input only ...

What is the solution for incorporating multiple elements in knockout's applyBindingsToNode function?

I am currently using knockout applyBindingsToNode to dynamically add and remove elements in order to update my html. I need to cut the binding, which is why I am utilizing applyBindingsToNode. In an example I have provided, if you click on the button "Reb ...

Use Javascript to display or conceal events on a fullcalendar interface

I am in the process of creating a religious calendar as part of a project that displays various events from major religions. Using the full calendar, I have included a "religion key" at the top of the calendar to differentiate between different faiths. My ...

The Angular Material date picker unpredictably updates when a date is manually changed and the tab key is pressed

My component involves the use of the Angular material date picker. However, I have encountered a strange issue with it. When I select a date using the calendar control, everything works fine. But if I manually change the date and then press the tab button, ...

Vue: Issue with Firebase Authentication REST API triggers 400 Bad Request Error

Here is the error message I am encountering: POST scheme https host identitytoolkit.googleapis.com filename /v1/accounts:signUp key AIzaSyAk1ueCLjDDWCNrt_23o5A4RCfeaYIlN6k Address 74.125.24.95:443 Status 400 Bad Request VersionHTTP/3 Transferred850 B ...

Utilizing the i18next instance for multiple purposes within an express application

I am working on internationalizing my express backend and have run into a challenge. I would like to: initialize my i18next instance in one central location reuse that instance throughout my codebase utilize the i18next instance in model code, not just i ...

What are the steps to restrict the scope of a <style> declaration in HTML?

Currently, I am in the process of creating a user interface for a webmail. Whenever I receive an email, I extract its content and place it within a <div> element for display purposes. However, one challenge that I am facing is that each email contain ...

Expand the initial expansion panel within an Angular Material accordion by opening the first attachment

In Angular Material expansion panels, the expanded input can be used to automatically open a specific panel when the page loads. However, in my dynamic accordion where all panels are optional, I want the first panel to be opened by default. I could manual ...

Using TypeScript: creating functions without defining an interface

Can function props be used without an interface? I have a function with the following properties: from - HTML Element to - HTML Element coords - Array [2, 2] export const adjustElements = ({ from, to, coords }) => { let to_rect = to.getBoundingC ...

Learn how to retrieve specific user information from a JSON file by implementing a button click feature within a custom directory using Angular.js

I am just starting to learn angular.js and I'm trying to figure out how to retrieve JSON data from a custom directory. My goal is to display the information of a specific user when a particular button is clicked, but so far I haven't been success ...

Using words instead of symbols to represent logical operators

When coding in C++, I typically prefer using the 'word' operators: not instead of ! and instead of && or instead of || I find it easier to read, especially when negating statements with not. Is there a similar approach possible in ...

Authentication Redirect Failure when using Passport to an absolute URL

I am looking to redirect the user to a different URL with the code/token received after logging into Facebook using Passport in Express.js. app.get('/auth/facebook/callback', function (req, res, next) { var authenticator = passport.authentic ...

What is the reason the 'Add' type does not meet the 'number' constraint?

I experimented with type gymnastics using Typescript, focusing on implementing mathematical operations with numeric literals. First, I created the BuildArray type: type BuildArray< Length extends number, Ele = unknown, Arr extends unknown ...

Sharejs has not been loaded on the client's side

Server var express = require('express'); var app = express(); var connect = require('connect'); var sharejs = require('share').server; var server = connect( connect.static(__dirname + '/public/client/') ); var o ...

Creating raw JavaScript from npm package:How to convert npm modules into plain

Is there a way to get a pre-compiled plain JavaScript file from the repository https://github.com/airbrake/airbrake-js? I'm looking for a solution without using bower, npm or any other tools - just a single JavaScript file. By the way: The file "http ...

Steps for incorporating the getElementByClassName() method

I have developed an application that features a list displayed as shown below: https://i.stack.imgur.com/BxWF2.png Upon clicking each tick mark, the corresponding Book name is added to a textbox below. I desire the tick mark to be replaced by a cross sym ...

Utilizing the $(this).text method in combination with the content class

In order for the text of the click function to be the final variable, I attempted using $(this).text, but unfortunately it did not produce the desired outcome. Placing the class at the end resulted in both p lines appearing. My goal is to only display the ...

Avoiding layout shift when a button is clicked in React JS

I am working on a Drawer example and following the instructions provided at https://mui.com/material-ui/react-drawer/ Everything is functioning as expected, but I am encountering an issue where my content shifts to the right when the drawer opens, and ret ...

Using ajax to send an array to PHP

I have an array named "heart" that is being sent via ajax... var heart = [31,32,33,34,35,36,37,38,39,42,43]; // Sending this data via ajax to php file/ $.ajax({ type: "POST", data:{ 'system': heart }, url: "login-function.php", success: f ...