Can Express.Multer.File be inserted into a FormData object easily?

Can anyone assist me in figuring out how to add a file of type Express.Multer.File into a FormData object?

Situation: I have received a file with the type Express.Multer.File (I am using nestjs and followed this part of the documentation: https://docs.nestjs.com/techniques/file-upload). I need to place it in a FormData object to send it to another API.

I attempted form.append('randomword', file); however, I am encountering the error:

TypeError: source.on is not a function
    at Function.DelayedStream.create (xxx/delayed-stream/lib/delayed_stream.js:33:10)
    at FormData.CombinedStream.append (xxx/combined-stream/lib/combined_stream.js:45:37)
...

I understand that I may be approaching this incorrectly, but I am unsure of the correct method. Any guidance would be greatly appreciated!

Answer №1

To create a new Form Data, you can utilize the buffer and originalname retrieved from multer.

Here is an example solution for sending only one file using the POST method:

router.post("/", multer().single("file"), async (req, res, next) => {

let formData = new FormData();
formData.append("yourFormDataKey", req.file.buffer, req.file.originalname)

//YOUR CODE USING THE FORM DATA GOES HERE//

}

Answer №2

I discovered a clever "solution" to tackle this issue.

  • Initially, I obtain the file in the form of Express.Multer.File.
  • Next, I store it by utilizing createWriteStream from fs.
  • Lastly, I introduce it to the FormData object using createReadStream method.

And voila! While not the most ideal approach, it serves as a workaround for now.

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

Expanding and collapsing multiple tables in Material-UI

I'm currently working on creating a collapsible table using MaterialUI. At the moment, all my slides have collapses but they are connected to one state for "open", so when I open one slide, all the other slides also open. Here is an example sandbox t ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

Executing a POST request with AJAX in jQuery to communicate across different domains and fetching XML data as

Is it possible to send an AJAX request using the POST method and receive XML as a response text? If so, please provide me with the steps to achieve this. For example: url : "http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate" data ...

Remove click event listeners from a specific element within a group of selected elements using D3

In my D3 class, I have a group of selectors that I want to remove the click event from: d3.selectAll('.selectors').on('click',function(){ //Remove the click event from the currently clicked element. }); I'm encountering tw ...

Implementing a JavaScript function to a button within an existing form in JSP - Best practices

Currently, I am working on developing multiple JSP pages and I encountered a requirement where I needed to add a function to a button within an already existing form. The challenge was that the form's submit button was configured to navigate to anothe ...

Implementing Dynamic Script Injection in Angular Controllers for Enhanced HTML Functionality

I'm a total beginner when it comes to Angular and frontend development, so please bear with me if my question seems basic: In my controller, I have the following code where I am populating the $window.user data that is being used in the script [2] ad ...

Exploring the World of React JS by Diving into Backend Data

Let's consider an application that consists of three pages: "HomePage" "PrivatePage" "UserManagementPage" In addition, there is a file called "BackendCommunication.js" responsible for handling communication with the backend. "Homepage.js" import Re ...

Facing difficulties in resetting the time for a countdown in React

I've implemented the react-countdown library to create a timer, but I'm facing an issue with resetting the timer once it reaches zero. The timer should restart again and continue running. Take a look at my code: export default function App() { ...

Assigning a changing label to a radio button

Looking to create a dynamic form where clicking a button calls a JavaScript function. Here's the code snippet: function addRadioButton(type){ var element = document.createElement("input"); //Set attributes for the element. element.setAttr ...

How to display a page outside the router-outlet in angular 4

I'm currently developing an angular 4 application and I am trying to figure out how to load the login.page.ts outside of the router-outlet This is what my home.component.html file looks like: <div class="container"> <top-nav-bar></ ...

Keycloak does not support using the updateToken() function within an asynchronous function

In our development of a Spring application with React/Redux frontend, we faced an issue with Keycloak authentication service. The problem arose when the access token expired and caused unexpected behavior in our restMiddleware setup. Here is a simplified v ...

How can you store previously calculated values in a costly recursive function in a React application?

Consider a scenario where there is a recursive callback function like the one shown below: const weightedFactorial = useCallback(n => { if (n === 0) { return 1; } return weight * n * weightedFactorial(n - 1); }, [weight]); Is it possible to ...

Mysterious and never-ending loop that seems to loop endlessly and eludes my

My prototype includes a method for adding callbacks: /* * Add a callback function that is invoked on every element submitted and must return a data object. * May be used as well for transmitting static data. * * The callback function is supposed to e ...

Issues with the Winston transport for Loggly are causing inconsistent performance

I have implemented Winston with 3 transports: Console, File, and Loggly (using https://github.com/loggly/winston-loggly-bulk). While the Console and File transports are functioning properly, I am facing an issue with the Loggly transport. It only logs my ...

Tips for obtaining validation errors on input elements in React when the input field is of type "file"

Currently, I am utilizing Material UI to cover the input component with icons. However, I have encountered an issue where there is an input element hidden and as a result, validation errors are not being displayed. The library I am using for validation i ...

JavaScript / html Error: function body missing closing curly brace

I encountered an error that I'm struggling to resolve: "SyntaxError: missing } after function body". Despite not having a function named 'body', I have attempted changing every instance of 'body' in my script. However, ...

What is the best way to make a CSS class appear in my javascript using the method I have been using before?

I am facing an issue in making this code work properly. It functions correctly for my caption element as there is only one caption tag in my HTML. However, the same code does not work for my TR element since it requires a for loop to iterate through multip ...

Delete the placeholder image from a div once live content has been inserted into it

If I have a container div that displays an image when empty, but I want to remove the image when content is dynamically added to the container, what would be the most effective way to do this with jQuery? The usual method of checking if the container' ...

What could be the reason for data-id coming back as undefined?

I'm having trouble figuring out why the code below isn't working for me. The console is showing 'undefined' for data-id. href='#detailsModal' class='btn btn-info btn-xs' data-toggle='modal' data-id='x ...

Retrieving dates from a database and populating them into a jQuery UI Picker using PHP

I need to retrieve dates from the database using PHP and highlight them in a datepicker. Here is how I am attempting to accomplish this: HTML Date: <input type="text" id="datepicker"> // Static dates // An array of dates var eve ...