The data stored in a FormGroup does not automatically transfer to FormData

I am currently facing an issue with uploading multi-part data to my API. To achieve this, I have created a FormData object for the upload process. Initially, I gather all the necessary user input data such as an image (file) and category (string). These values are extracted from the template and stored in categoryForm: FormGroup. However, when attempting to transfer these values to a FormData object for submission to the API, I encounter the following error:

{"src":["No file was submitted."],"tag":["This field is required."]}

Upon inspecting the browser console, it becomes apparent that the FormData object remains empty. Despite successfully logging the categoryForm values and confirming that they contain the expected data, the values do not seem to be reassigned to formData. The issue appears to lie within the section where the values of categoryForm should be assigned to formData. I believe there are no issues with the categoryForm or the template, as logging them separately displays the correct data for both category and image. Could someone provide assistance in resolving this problem?

Code Snippet

  apiSubmit() {
      console.log(this.categoryForm.value) // returns values
      console.log(this.categoryForm.get('category').value); // returns values
      console.log(this.categoryForm.get('image').value); // returns values
      
      const formData = new FormData();
      formData.append('category', this.categoryForm.get('category').value);
      formData.append('image', this.categoryForm.get('image').value);
      console.log(formData); // doesn't return values
    
      this.http.post<any>(this.url, formData, httpOptions).subscribe(
        (res) => console.log(res),
        (err) => console.log(err)
      );
    }]

Browser Console Logs

https://i.sstatic.net/Jv2pK.png

Answer №1

The approach you've taken may not be suitable for the specific scenario due to using append on the object. Instead, consider using a constructor for FormData that takes this.categoryForm.value as arguments or parameters and assigns it to a variable. Alternatively, you can directly utilize this.categoryForm.value in a post method without using FormData.

For example:

export class FormData{
   image: any;
   category: string;
  
  constructor(args){
     this.image = args.image;
     this.category = args.category;
  }
}

You can then create an object like

const formData = new FormData(this.categoryForm.value);

Answer №2

Dealing with image uploads using form data can be tricky at times. Instead of manually appending key-value pairs, you can simplify the process by using an npm package called 'serialize' to convert objects to form data effortlessly. To view the values in the console, iterate through formData.values() and log each value.

In my experience, handling image uploads on Ionic is most efficient when using a 'base64' encoded string. I recommend adjusting your backend to receive 'base64' encoded strings for smoother integration.

Many camera native plugins for Ionic return either FILE_URI or BASE64 formats. Take, for instance, the camera native plugin:

To implement this according to the documentation, initiate the installation ionic camera native

openGallery() {
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
    };

    this.camera.getPicture(options).then((imageData) => {
     const base64Image = 'data:image/jpeg;base64,' + imageData;
     console.log(base64Image);
     this.categoryForm.value.image = base64Image;
    }, (err) => {
     console.log(err);
    });
  }

By setting up your backend to accept base64 strings in conjunction with the steps above, your image upload functionality should operate smoothly.

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

Solving the Issue of Assigning a Random Background Color to a Dynamically Created Button from a Selection of Colors

Trying to create my own personal website through Kirby CMS has been both challenging and rewarding. One of the features I'm working on is a navigation menu that dynamically adds buttons for new pages added to the site. What I really want is for each b ...

Exploring routing within a Higher Order Component in React Native

I am looking to implement a file existence check on every page of my app. The idea is that if a specific file exists, the user should be redirected to another page. One solution I have considered is using a Higher Order Component (HOC) for this purpose. A ...

Setting up jsonServer in gulp with typescript: A guide

Previously, I had set up a json server and used the following code to start it: I found guidance in this GitHub repository. Starting angular2 project with gulp gulp-live-server.js var gulpCore = require('gulp'); var gulpParam = require('g ...

Removing multiple httpparams in Angular: A step-by-step guide

When working with APIs, there are times when custom parameters are added for specific use cases that do not need to be sent to the backend. In such situations, it is necessary to delete these parameters before sending the request to the backend. Url: https ...

Invoke the function once the database information has been retrieved

I am new to Node.js and I am attempting to execute a function after running a select query using the code below: private displayUserInfo(): any { let connect = this.connect(); connect.connect(function(err: any) { if (err) throw err; ...

The resize function fails to trigger when it is required

Struggling to get this code working properly. If the window width is greater than 800, I want 6 images with a red background. If the window width is less than 800, I want 4 images with a blue background. I need this functionality to work both on r ...

Exploring the functionality of multiple checkboxes in Next.js 14, the zod library, shadcn/ui components, and react-hook

I'm currently working on a form for a client where one of the questions requires the user to select checkboxes (or multiple checkboxes). I'm still learning about zod's schema so I'm facing some challenges in implementing this feature. I ...

What is the reason that .bin/www is recognized as a JavaScript file even though it does not have the .js extension when utilizing express-generator

Can you explain why .bin/www is recognized as a JavaScript file by express-generator even without the .js extension? Whenever I create a bin/ folder with a www file inside, it's automatically identified as a JavaScript file despite the missing .js ex ...

Is there a way to automatically refresh a page as soon as it is accessed?

My goal is to create a page refresh effect (similar to pressing Command+R on Mac OS) when navigating to a certain page. For instance: Currently, when I navigate from "abc.com/login" to "abc.com/dashboard" after successfully logging in, the transition occ ...

Automated logout feature will be enabled if no user interaction is detected, prompting a notification dialog box

Here is my working script that I found on this site. After a period of idle time, an alert message will pop up and direct the user to a specific page. However, instead of just the alert message, I would like to implement a dialog box where the user can ch ...

When attempting to insert data retrieved from axios into a table within a React component, the data is coming back as

Hi there! Currently, I'm in the process of developing an application that retrieves data from an API and my goal is to display it in a Material UI Table within a React environment. Strange issue I'm encountering: when I use console.log to check ...

The onPlayerReady function in the YouTube API seems to be experiencing a delay and

After following a tutorial on integrating the YouTube API into my website, I encountered difficulties trying to play a YouTube video in fullscreen mode when a button is pressed. Despite following the provided code closely, I am unable to get it to work as ...

Angular relative routes are failing to function

I am currently working on implementing a feature module in my project and following the documentation provided. My crisis-routing.module file looks like this: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from ' ...

Is there a way to compare the elements of an array with those of another array containing nested arrays in order to identify matching results?

Every user in our database has specific skills assigned to them. We maintain a list of available skills with unique IDs. The objective is to filter users based on the skill we are interested in, like displaying all Janitors. We are utilizing Vue.js and im ...

Getting the latest version number of an app from the Google Play Store for an IONIC project

Is there a way to determine if the app needs to be updated from the playstore? I want to display a message prompting users to update their app. Any suggestions on how to implement this feature? ...

Using a loop to chain jQuery's .when().then() method and ensuring a fixed final call at the end of the

The solution that closely matches my issue can be found at One common use case for .then is chaining ajax requests: $.ajax({...}).then(function(){ return $.ajax({...}); }).then(function(){ return $.ajax({...}); }).then(function(){ retu ...

The behavior of Angular redirecting after login is quite unusual

I have an Angular component named Login. After a successful login, I want the page to refresh along with the navigation bar and then redirect to another component called 'welcome'. Here is the code snippet: import { TokenStorageService } from ...

Tips for ensuring a document stays at the top of my collection when performing an update

Whenever I make changes to a document, it always ends up at the bottom of my collection. Is there a way to prevent this from happening? try { await Card.update({_id: fixedUrl}, {$push:{'comments': data}}) } catch (err) { console.log(err ...

Executing two distinct SQL queries within one nodejs function

I'm facing an issue with updating two tables in my database - the stockmaster table and the prodstock table. I've been trying to run a query using a function to update both tables simultaneously, but unfortunately, it's not working as expect ...

When attempting to retrieve data saved to req.session with express-session from a different endpoint, the data appears to be

While working on my project with express-session, I encountered a peculiar issue. I am saving the currently logged in user to the session, but when I try to access the currentUser key on the get route, I find that the value is an empty object. Strangely, i ...