Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save FormData with File Upload in Angular 5

I am trying to save files along with FormData in Angular 5. I can get the single file, but have no idea how to get all the files uploaded. I have three image files and input fields, tried searching examples. But only got for multiple file uploads. I want to upload each and every single file from this form.

Below is my code :

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Location } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { Category } from '../../../shared/services/categories/category';
import { CategoriesService } from '../../../shared/services/categories/categories.service';

@Component({
  selector: 'app-add-category',
  templateUrl: './add-category.component.html',
  styleUrls: ['./add-category.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class AddCategoryComponent implements OnInit {
  
  category: Category = new Category();
  fileToUpload: File = null;
  
  constructor(
    private categoriesService: CategoriesService,
    private route: ActivatedRoute,
    private location: Location  
  ) { }

  ngOnInit() {
  }

  goBack(): void {
    this.location.back();
  }

  handleFileInput(files: FileList) {
    console.log(files);
  }

  addCategory() {
    console.log(this.category);
    this.categoriesService.createCategory(this.category).subscribe(() => this.goBack());
  }

}
          <h3 class="box-title">Category</h3>

        <form role="form" (ngSubmit)="addCategory()" #categoryForm="ngForm">

              <div class="box-body">

                <div class="row">
                  <div class="col-lg-6">
                  <label for="Category Name">Name</label>
                  <input type="text" class="form-control" [(ngModel)]="category.category_name" name="category_name" id="category_name" placeholder="Enter Category Name" required="">
                </div>

                <div class="col-lg-6">
                  <label for="Category Path">Path</label>
                  <input type="text" class="form-control" [(ngModel)]="category.category_path" name="category_path" id="category_path" required="">
                </div>
              </div>
            </div>
            <br/>

            <div class="form-group">
                  <label for="Category Description">Description</label>
                  <textarea rows="3" [(ngModel)]="category.category_description" name="category_description" id="category_description" class="form-control" required=""></textarea>
            </div>
                
            <div class="col-lg-12 text-center">
                <input type="file" [(ngModel)]="category.category_banner" (change)="handleFileInput($event.target.files)" class="custom-file-input" name="category_banner" id="category_banner">
                <label class="custom-file-label" for="customFile">Banner</label>
            </div>
            <br/>

            <div class="form-group">
              <label for="Category Banner Code">Banner Code</label>
              <textarea rows="3" [(ngModel)]="category.category_banner_code" name="category_banner_code" id="category_banner_code" class="form-control" required=""></textarea>
            </div>
            
            <br/>
            
            <div class="col-lg-12">
                <input type="file" [(ngModel)]="category.category_image" (change)="handleFileInput($event.target.files)" class="custom-file-input" name="category_image" id="category_image">
                <label class="custom-file-label" for="customFile">Image</label>
            </div>
        
            <br/>

            <div class="col-lg-12">
                <input type="file" [(ngModel)]="category.category_icon" (change)="handleFileInput($event.target.files)" class="custom-file-input" name="category_icon" id="category_icon">
                <label class="custom-file-label" for="customFile">Icon</label>
            </div>

              <div class="form-group">
              <label for="Category Meta Title">Meta Title</label>
              <input type="text" [(ngModel)]="category.category_meta_title" class="form-control" name="category_meta_title" id="category_meta_title" placeholder="Enter Meta Title" required="">
            </div>

            <div class="form-group">
              <label for="Category Meta Description">Meta Description</label>
              <input type="text" [(ngModel)]="category.category_meta_decription" class="form-control" id="category_meta_description" name="category_meta_description" placeholder="Enter Meta Description" required="">
            </div>

            <div class="form-group">
              <label for="Category Meta Keyword">Meta Keyword</label>
              <input type="text" [(ngModel)]="category.category_meta_keyword" class="form-control" id="category_meta_keyword" name="category_meta_keyword" placeholder="Enter Meta Keyword" required="">
            </div>

            <div class="form-group">
             
              <div class="row">
                 <div class="col">Featured :</div>
                <div class="col">
                <label class="radio-inline" for="Category Featured">
                  <input type="radio" [(ngModel)]="category.category_featured" name="category_featured" id="category_featured" value="1" required="">Yes
                </label>
              </div>

              <div class="col">
                <label class="radio-inline" for="Category Featured">
                  <input type="radio" [(ngModel)]="category.category_featured" name="category_featured" id="category_featured" value="0" required="">No
                </label>
            </div>
            </div>
            </div>
              
            <input type="hidden" [(ngModel)]="category.category_status" name="category_status" id="category_status" value="1">

              <div class="box-footer col-md-12">
                <button type="submit" class="btn btn-primary">Submit</button>
              </div>
            </form>
like image 952
Kamlesh Katpara Avatar asked Jan 26 '18 20:01

Kamlesh Katpara


People also ask

How to upload files in angular using formdata?

How to Upload Files in Angular using FormData? 1 Step 1) Import required modules#N#To enable a form to upload files to a remote server using the HTTP post method in... 2 Step 2) Adding a Form in Component Template#N#Add a simple Form in a component template HTML with [formGroup] and... 3 Step 3) Update Component class file More ...

How to send formdata to the file upload server?

After creating the service that takes care of sending FormData to the file upload server, let’s now create the UI for uploading images to the server. Open the src/app/home/home.component.ts file, and start by adding the following imports: Next, define the fileUpload and files variables and inject UploadService as follows:

Which version of angular is this post compatible with?

This Angular post is compatible with Angular 4 upto latest versions, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11, Angular 12 and Angular 13 We are going to create a simple form that will have a file input control to select a file which will be uploaded by clicking on a button.

How do I import components in Angular Material?

Each Angular Material component exists in its separate module that you need to import before you can use the component. Open the src/app/app.module.ts file and add the following imports: These are the modules we imported:


1 Answers

I recently had a similar issue. This can be solved by setting the content type of header as null in the Angular code. Attaching the code snippet of Angular5 and spring boot backend.

let headers = new HttpHeaders();
//this is the important step. You need to set content type as null
headers.set('Content-Type', null);
headers.set('Accept', "multipart/form-data");
let params = new HttpParams();
const formData: FormData = new FormData();
for (let i = 0; i < this.filesList.length; i++) {
  formData.append('fileArray', this.filesList[i], this.filesList[i].name);
} 
formData.append('param1', this.param1);
formData.append('param2', this.param2);
this.http.post(this.ROOT_URL + this.SERVICE_ENDPOINT, formData, { params, headers }).subscribe((res) => {
    console.log(res);
});



In the spring boot backend, you need to have the controller as - 

@RequestMapping(value = "/uploadAndSendEmail", method = RequestMethod.POST, consumes= "multipart/form-data")    
public ResponseEntity<String> uploadAndSendEmail(@RequestParam("fileArray") MultipartFile[] fileArray, 
        @RequestParam(value = "param1", required = false) String param1,
        @RequestParam(value = "param2", required = false) String param2) {
        //do your logic
        }
like image 160
chaitanya Rudrabhatla Avatar answered Nov 10 '22 19:11

chaitanya Rudrabhatla