Nest Js file uploads encountering issues when used in conjunction with JavaScript FormData functionality

I'm encountering some difficulties in parsing a request sent from the front-end using FormData. Below is an example request generated from Postman for Axios in node.js. Interestingly, when I use the same request in the Postman app, it functions as intended.

This code snippet showcases how to generate a request from Postman feature in frontend:

var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');
var data = new FormData();
data.append('file', fs.createReadStream('/some_file.jpg')); **//Electron allows client-side access to FileSystem**
data.append('resizeLargeImage[width]', '1920');
data.append('resizeLargeImage[height]', '1080');
data.append('resizeLargeImage[type]', 'cover');

var config = {
  method: 'post',
  url: 'localhost:3030/api/v1/optimize-single',
  headers: { 
    'x-api-key': '123', 
    ...data.getHeaders()
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

The backend implementation is as follows:

@Post('/optimize-single')
 @UseInterceptors(FileInterceptor('file'))
 async uploadFile(
   @UploadedFile() file: FileDto,
   @Body() body: UploadFileParametersDto,
   @Res() response: Response,
 ): Promise<any> {
   console.log('file', file, 'body', body);
   **//While "body" is a null Object, "file" turns out to be undefined**

   return await this.appService.uploadFile(file, body, response);
 }

I'm puzzled as to why Nest isn't able to recognize this type of request. Any insights would be greatly appreciated!

Thank you!

Answer №1

I was able to solve the problem on my own.

When working in the Renderer process, you can make it work by connecting the file as a blob.

const fileBuffer = fs.readFileSync(filePath);
const fileName = path.basename(filePath);
const blob = new Blob([fileBuffer], {
   type: mime.lookup(filePath),
});
formData.append('file', blob, fileName);

If you transfer the same feature to the Main process, it will function as expected with

data.append('file', fs.createReadStream('/some_file.jpg'));

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

Creating one div to initiate the contents to fadeToggle and another div to cease the fadeToggle animation utilizing the setInterval function in JavaScript

Here is the link to my Fiddle: http://jsfiddle.net/tmanundercover/62ap2/ CSS #targetedDiv, #otherDiv { border: 1px solid; } HTML <div id="targetedDiv">&nbsp<span id="fakeCursor">|</span></div> <br> <div id="othe ...

Trouble with maps not showing up and the console isn't showing any errors when using @react-google-m

Currently, I am facing an issue while trying to integrate Google Maps by following a blog post that provides instructions on next13 TypeScript. Despite reaching the point where the maps should be displayed, nothing appears on the screen. Surprisingly, ther ...

Develop interactive web applications using Typescript

Having difficulty compiling and executing the project correctly in the browser. The "master" branch works fine, but I'm currently working on the "develop" branch. It's a basic web project with one HTML file loading one TS/JS file that includes i ...

What is the best way to define an Array of Objects in a TypeORM Graphql Schema?

I'm currently working on a project involving 2 Postgres Models - users and posts. Each user can have multiple posts, creating a One to Many Relation between the two. My goal is to create a user profile function that allows me to access data of a singl ...

What is the best way to modify multiple properties of a Map object using Immutable.js?

I'm facing a challenge with this map I have Immutable.Map({ winChance : 49.99, rollOver : 49.99, payOut : 1.98, rollToggle : 1,}) How can I efficiently update all the values in this map at once? I need to incorporate it into a function. I am lookin ...

Is ngSwitch in Angular causing the label element to disappear?

I am using AngularJS to generate form elements dynamically based on an array containing form details such as input type and value. For example, here is the code snippet I have for creating a text input field: <div ng-repeat="input in input_array"> ...

How to create an array of objects in TypeScript

I am looking to define an array of objects in TypeScript. Here is my example: const a = [{ name: 1, age: 2, car1: 8, car2: 8, car3: 8, name4: 1, age4: 2, car41: 8, car42: 8, car34: 8, }, { name: 1, age: 2, car1: 8, car2: 8, ...

Combining multiple data types in an AJV array

Imagine you have the following defined type: type MixedArray = Array<number | string>; Now, let's say you have some sample data that needs to be validated: [ 'dfdf', 9, 0, 'sdfdsf' ] How can you create an Ajv JSONSchemeType ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

Utilize AngularJS to modify the appearance of text

Just starting out with AngularJS and I need to achieve the following task. I have a text that says "bob" and two buttons, one for bold and one for italic. When the bold button is clicked, I want to make the text BOB bold and when the italic button is click ...

Issue encountered when attempting to utilize Next-Auth alongside Credentials Provider to authenticate within a pre-existing system

I am currently utilizing the Next-Auth Credentials provider for authentication purposes through our existing API. Following the guidelines provided at https://next-auth.js.org/configuration/callbacks the code snippet used is as follows: callbacks: { ...

The @input function in Vue.js is currently only triggered after the user has focused out, but I need it to be called while the user is

When working with @input on an input field in Vue.js, I am facing an issue where the assigned function is only called after the user has stopped typing and the focus is out of the input field. Essentially, it is triggered on onFocusout. What I actually wan ...

Utilizing class references within a method

I have been developing a script that is designed to dynamically load content into multiple predefined DIVs located in the topbar section of my website. Within the Topbar Object, there is an object called Ribbon which contains functions for manipulating on ...

The 'data' property is absent in the 'never[]' type, whereas it is necessary in the type of product data

Hello, I am new to TypeScript and I'm struggling with fixing this error message: Property 'data' is missing in type 'never[]' but required in type '{ data: { products: []; }; }'. Here is my code snippet: let medias :[] ...

What is the reason JSON.parse fails to convert a string into a JSON object?

I attempted to convert a string into a JavaScript object using JSON.parse, however, it seems to be unsuccessful. After trying various methods, I did not receive any output in the console.log and no error messages were displayed. JSON.parse(`{'exp&apo ...

Using AJAX to Post Data with Relative Path in ASP.NET MVC 5

I have been developing an MVC 5 web application that utilizes AJAX Posts to invoke Controller Actions. For example, I have a controller named "Account" with an action called "Create". In my Account/Index view, which is rendered by accessing an Account/Ind ...

Ways to position the navigation menu alongside a search bar and a dropdown tab?

My navigation bar includes a search form, multiple links, and a dropdown link leading to additional links. Unfortunately, I'm struggling to align everything on the same line within the navbar. This is the current output: View My HTML Page Below is ...

Is there a way for me to identify the vertical gaps in my code using JavaScript?

Within this specific HTML document, there are multiple div elements that have an absolute positioning applied to them I am looking to develop a JavaScript code that can determine the row of each individual div. I define a row as any space on the vertical ...

"What is the best way to determine the data type of an object retrieved from an API in TypeScript

Hey there, I'm currently developing a web application using Angular 2 and I'm focusing on implementing an exception handling mechanism. To achieve this, I've created a model that mirrors the object structure I will receive from the server (E ...

Strategies for Managing Output Event Prioritization in Angular Using RxJs Based on Trigger Sequence

Within my Angular Application, there is a widget with two event outputs originating from a third-party library. Unfortunately, I am unable to modify its behavior. <myWidget (onAlwaysEvent)="onAlwaysEvent($event)" (onSometimesEvent)="onSometimesEven ...