Angular File Upload Partial Form Data Content Type Undefined
In this tutorial, I will testify you way to build an Angular 12 File upload to Rest API example using Bootstrap, HttpClient, FormData and Progress Bar.
More Exercise:
– Angular 12 Login and Registration example with JWT & Web Api
– Angular 12 CRUD Application case with Web API
– Angular 12 Form Validation example (Reactive Forms)
– Using Cloth: Angular Cloth 12 File upload example with progress bar
Serverless with Firebase:
Angular 12 Upload File to Firebase Storage instance
Newer version: Angular 13 File upload example with progress bar & Bootstrap
Overview
We're gonna create an Athwart 12 File upload to Residuum API application in that user can:
- come across the upload process (pct)
- view all uploaded files
- download past clicking on the file name
Technology
- Angular 12
- RxJS 6
- Bootstrap 4
Residuum API for File Upload & Storage
Here is the API that our Athwart App will work with:
Methods | Urls | Actions |
---|---|---|
POST | /upload | upload a File |
Become | /files | get List of Files (name & url) |
Go | /files/[filename] | download a File |
You tin can find how to implement the Rest APIs Server at ane of post-obit posts:
– Node.js Express File Upload Rest API example
– Node.js Limited File Upload to MongoDB example
– Node.js Limited File Upload to Google Cloud Storage example
– Spring Kicking Multipart File upload (to static folder) example
Or: Spring Kick Multipart File upload (to database) example
Setup Angular 12 Projection
Allow's open up cmd and employ Angular CLI to create a new Angular 12 Projection as post-obit command:
ng new Angular12FileUpload ? Would you like to add Athwart routing? No ? Which stylesheet format would you similar to employ? CSS
We also demand to generate some Components and Services:
ng g s services/file-upload ng 1000 c components/file-upload
Now you tin can see that our project directory structure looks similar this.
Angular 12 App for uploading File with HttpClient
Let me explicate it briefly.
– We import necessary library, components in app.module.ts.
– file-upload.service provides methods to save File and get Files from Rest API Server using HttpClient
.
– file-upload.component contains upload form, progress bar, display of list files.
– app.component is the container that nosotros embed all components.
– index.html for importing the Bootstrap.
Gear up App Module for HttpClient
Open up app.module.ts and import HttpClientModule
:
import { NgModule } from '@angular/cadre'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { FileUploadComponent } from './components/file-upload/file-upload.component'; @NgModule({ declarations: [ AppComponent, FileUploadComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Add Bootstrap to the project
Open up alphabetize.html and add following line into <head>
tag:
<!DOCTYPE html> <html lang="en"> <head> ... <link blazon="text/css" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.i/css/bootstrap.min.css" /> </head> ... </html>
Create Athwart Service for Upload Files
This service volition use Angular HttpClient
to ship HTTP requests.
There are two functions:
-
upload(file)
: returnsObservable<HttpEvent<any>>
that we're gonna use for tracking progress -
getFiles()
: returns a listing of Files' information equallyObservable
object
services/file-upload.service.ts
import { Injectable } from '@athwart/core'; import { HttpClient, HttpRequest, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export grade FileUploadService { private baseUrl = 'http://localhost:8080'; constructor(private http: HttpClient) { } upload(file: File): Observable<HttpEvent<any>> { const formData: FormData = new FormData(); formData.suspend('file', file); const req = new HttpRequest('POST', `${this.baseUrl}/upload`, formData, { reportProgress: true, responseType: 'json' }); render this.http.asking(req); } getFiles(): Observable<any> { render this.http.get(`${this.baseUrl}/files`); } }
– FormData
is a data construction that can be used to store key-value pairs. We use information technology to build an object which corresponds to an HTML form with append()
method.
– Nosotros fix reportProgress: true
to exposes progress events. Notice that this progress issue are expensive (change detection for each event), so you should only use when you want to monitor it.
– We call the asking(PostRequest)
& get()
method of HttpClient
to transport an HTTP POST & Get request to the Spring Boot File Upload server.
Create Component for Upload Files
Let's create a File Upload UI with Progress Bar, Card, Button and Bulletin.
First nosotros need to use the following imports:
file-upload.component.ts
import { Component, OnInit } from '@angular/core'; import { HttpEventType, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { FileUploadService } from 'src/app/services/file-upload.service';
And then we define the some variables and inject FileUploadService
as follows:
export form FileUploadComponent implements OnInit { selectedFiles?: FileList; currentFile?: File; progress = 0; message = ''; fileInfos?: Observable<any>; constructor(private uploadService: FileUploadService) { } }
Next we ascertain selectFile()
method. It helps usa to get the selected Files.
selectFile(issue: any): void { this.selectedFiles = event.target.files; }
Next we write upload()
method for upload file:
export class FileUploadComponent implements OnInit { selectedFiles?: FileList; currentFile?: File; progress = 0; message = ''; fileInfos?: Observable<any>; constructor(individual uploadService: FileUploadService) { } selectFile(event: any): void { this.selectedFiles = event.target.files; } upload(): void { this.progress = 0; if (this.selectedFiles) { const file: File | null = this.selectedFiles.item(0); if (file) { this.currentFile = file; this.uploadService.upload(this.currentFile).subscribe( (event: any) => { if (event.type === HttpEventType.UploadProgress) { this.progress = Math.round(100 * event.loaded / effect.full); } else if (event instanceof HttpResponse) { this.message = consequence.torso.message; this.fileInfos = this.uploadService.getFiles(); } }, (err: any) => { console.log(err); this.progress = 0; if (err.fault && err.fault.message) { this.bulletin = err.error.message; } else { this.message = 'Could non upload the file!'; } this.currentFile = undefined; }); } this.selectedFiles = undefined; } } }
We employ selectedFiles
for accessing current File as the starting time Particular. Then nosotros call uploadService.upload()
method on the currentFile
.
The progress will exist calculated basing on event.loaded
and event.total
.
If the transmission is washed, the upshot will be a HttpResponse
object. At this time, nosotros call uploadService.getFiles()
to get the files' information and assign the result to fileInfos
variable.
We also need to do this work in ngOnInit()
method:
ngOnInit(): void { this.fileInfos = this.uploadService.getFiles(); }
Now we create the HTML template of the Upload File UI. Add the following content to file-upload.component.html file:
<div form="row"> <div grade="col-8"> <label class="btn btn-default p-0"> <input type="file" (change)="selectFile($event)" /> </characterization> </div> <div grade="col-4"> <button course="btn btn-success btn-sm" [disabled]="!selectedFiles" (click)="upload()"> Upload </button> </div> </div> <div *ngIf="currentFile" class="progress my-iii"> <div class="progress-bar progress-bar-info progress-bar-striped" office="progressbar" attr.aria-valuenow="{{ progress }}" aria-valuemin="0" aria-valuemax="100" [ngStyle]="{ width: progress + '%' }" > {{ progress }}% </div> </div> <div *ngIf="message" class="alert alarm-secondary" role="alert">{{ message }}</div> <div class="card mt-3"> <div class="menu-header">List of Files</div> <ul class="listing-grouping list-group-flush" *ngFor="let file of fileInfos | async" > <li grade="list-group-item"> <a href="{{ file.url }}">{{ file.name }}</a> </li> </ul> </div>
Add Upload File Component to App Component
Open app.component.html and embed the FileUpload Component with <app-file-upload>
tag.
<div class="container" manner="width:600px"> <div form="my-3"> <h3>bezkoder.com</h3> <h4>{{ title }}</h4> </div> <app-file-upload></app-file-upload> </div>
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 12 File Upload'; }
Run the App
You lot can observe how to implement the Rest APIs Server at one of post-obit posts:
– Node.js Express File Upload Remainder API example
– Node.js Express File Upload to MongoDB example
– Node.js Express File Upload to Google Deject Storage example
– Spring Boot Multipart File upload (to static folder) example
Because nosotros configure CORS for origin: http://localhost:8081
, so you need to run Angular 12 Customer with control:
ng serve --port 8081
Open Browser with url http://localhost:8081/
and bank check the issue.
Further Reading
- https://angular.io/api/common/http/HttpRequest
- Angular 12 Login and Registration instance with JWT & Spider web Api
- Athwart 12 Crud Application case with Web API
- Angular 12 Class Validation example (Reactive Forms)
- Angular 12 + Spring Kick: File upload example
- Angular 12 + Node.js Express: File Upload example
Conclusion
Today we're learned how to build an example for File upload to Rest API with Progress Bar using Angular 12 and FormData. We also provide the ability to show listing of files, upload progress using Bootstrap, and to download file from the server.
If yous desire to upload multiple files at in one case like this:
You lot can find the education here:
Angular 12 Multiple Files upload example with Progress Bar
Or Serverless with Firebase:
Angular Upload File to Firebase Storage instance
Happy Learning! See you again.
Source Code
The source code for the Angular 12 App is uploaded to Github.
Using Fabric: Athwart Fabric 12 File upload case with progress bar
Source: https://www.bezkoder.com/angular-12-file-upload/
0 Response to "Angular File Upload Partial Form Data Content Type Undefined"
Post a Comment