Search code examples
node.jsangularfilemultipartform-data

How to Send Image , Pdf and Few Parameters together From Angular to Node.Js Server


I am using Angular Material For getting Position of Draggable Image , getting input type file(pdf) from User and Images Stored in ./assets/emojis/. I am able to send Pdf from Angular to Node using ng2-file-upload and multer. FrontEnd

<input (change)="onFileSelected()" ng2FileSelect [uploader]="uploader" type="file" id="file">
<ion-button class="input-group-text upload" (click)="uploader.uploadAll()" >Upload</ion-button>

Backend

app.post('/api/upload', upload.single('pdf'), function (req, res) {
    console.log('File is available!');
    return res.send({
      success: true
    })
  });

Now i have image path selected by User at assets

imagePathToUpload:string = './assets/emojis/'+this.selectedEmoji
topPosition:number = this.topPos
leftPosition:number = this.leftPos

How can i send all these data together to Server , there is one way FormData but i dont understand how to use it. Objective is Send Image , Pdf , left and top position to server. Any Advice would be Appreciated.


Solution

  • To send multiple types of data (such as images, PDFs, and additional metadata like position) to the server in an Angular application, you can indeed use FormData. Here's how you can do it:

    1. Prepare Data: Before sending the data, make sure you have all the required data ready, including the image, PDF file, and additional metadata like the top and left positions.
    2. Create FormData Object: Create a new FormData object and append all the data you want to send to the server.
    3. Send Data to Server: Use Angular's HTTP client (HttpClient) to send the data to the server.

    Find below example code

    <input (change)="onFileSelected($event)" type="file" id="file">
    <ion-button class="input-group-text upload" (click)="uploadData()">Upload</ion-button>
    
    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-file-upload',
      templateUrl: './file-upload.component.html',
      styleUrls: ['./file-upload.component.css']
    })
    export class FileUploadComponent {
      selectedPdf: File; // To store the selected PDF file
      selectedImage: File; // To store the selected image file
      topPosition: number; // Assuming these are initialized elsewhere in your code
      leftPosition: number; // Assuming these are initialized elsewhere in your code
    
      constructor(private http: HttpClient) {}
    
      // Method to handle file selection
      onFileSelected(event: any) {
        const file = event.target.files[0];
        // Check if file is a PDF or an image
        if (file.type === 'application/pdf') {
          this.selectedPdf = file;
        } else if (file.type.startsWith('image/')) {
          this.selectedImage = file;
        } else {
          console.error('Unsupported file type');
        }
      }
    
      // Method to upload data to the server
      uploadData() {
        if (!this.selectedPdf || !this.selectedImage) {
          console.error('Please select both a PDF file and an image');
          return;
        }
        
        // Prepare data
        const formData = new FormData();
        formData.append('pdf', this.selectedPdf);
        formData.append('image', this.selectedImage);
        formData.append('topPosition', this.topPosition.toString());
        formData.append('leftPosition', this.leftPosition.toString());
    
        // Send data to server
        this.http.post('/api/upload', formData).subscribe(
          (response) => {
            console.log('Data successfully sent to server:', response);
          },
          (error) => {
            console.error('Error sending data to server:', error);
          }
        );
      }
    }