Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can send form data to Spring Boot 2.7 and upload a file in Angular 13 by creating a form in HTML and using the FormData object in JavaScript.

First, create an HTML form:

<form #fileUploadForm="ngForm" (ngSubmit)="submitForm()">
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" name="name" ngModel>
  </div>
  <div class="form-group">
    <label for="file">File</label>
    <input type="file" class="form-control-file" id="file" name="file" (change)="onFileSelect($event)">
  </div>
  <button type="submit" class="btn btn-primary" [disabled]="!fileToUpload">Submit</button>
</form>

In your component, you can use the FormData object in the submitForm() method:

export class FileUploadComponent {
  fileToUpload: File | null = null;
  formData: FormData = new FormData();

  constructor(private http: HttpClient) {}

  onFileSelect(event: any) {
    if (event.target.files.length > 0) {
      this.fileToUpload = event.target.files[0];
      this.formData.set('file', this.fileToUpload);
    }
  }

  submitForm() {
    const name = this.formData.get('name');
    this.formData.append('name', name);

    this.http.post('/api/upload', this.formData).subscribe(res => {
      console.log(res);
    });
  }
}

In this example, the onFileSelect() method is called when the user selects a file. The selected file is stored in the fileToUpload variable, and it is appended to the formData object using the set() method.

The submitForm() method is called when the user submits the form. It retrieves the name value from the formData object using the get() method, appends it to the formData object using the append() method, and sends it to the server using the HttpClient post() method.

On the server side, you can create a controller to handle the file upload:

@RestController
@RequestMapping("/api")
public class FileUploadController {

  @PostMapping("/upload")
  public ResponseEntity<String> handleFileUpload(@RequestParam("name") String name,
                                                  @RequestParam("file") MultipartFile file) throws IOException {
    // Save file to disk or database
    return ResponseEntity.ok("File uploaded successfully");
  }
}

In this example, the handleFileUpload() method takes two parameters: the name parameter, which is retrieved from the form data, and the file parameter, which is the uploaded file. You can handle the file in any way you wish, such as saving the file to disk or database. The method returns a ResponseEntity object with an OK status code and a message indicating that the file was uploaded successfully.