Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / File Upload In Angular?

File Upload In Angular?

August 20, 2021 by James Palmer

Angular 2 provides good support for uploading files. No third party library is required.

fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append(‘uploadFile’, file, file.name);
let headers = new Headers();
/** In Angular 5, including the header Content-Type can invalidate your request */
headers.append(‘Content-Type’, ‘multipart/form-data’);
headers.append(‘Accept’, ‘application/json’);
let options = new RequestOptions({ headers: headers });
this.http.post(`${this.apiEndPoint}`, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log(‘success’),
error => console.log(error)
)
}
}

using @angular/core”: “~2.0.0” and @angular/http: “~2.0.0”

From the answers above I build this with Angular 5.x
Just call uploadFile(url, file).subscribe() to trigger an upload
import { Injectable } from ‘@angular/core’;
import {HttpClient, HttpParams, HttpRequest, HttpEvent} from ‘@angular/common/http’;
import {Observable} from “rxjs”;

@Injectable()
export class UploadService {

constructor(private http: HttpClient) { }

// file from event.target.files[0]
uploadFile(url: string, file: File): Observable> {

let formData = new FormData();
formData.append(‘upload’, file);

let params = new HttpParams();

const options = {
params: params,
reportProgress: true,
};

const req = new HttpRequest(‘POST’, url, formData, options);
return this.http.request(req);
}
}

Use it like this in your component
// At the drag drop area
// (drop)=”onDropFile($event)”
onDropFile(event: DragEvent) {
event.preventDefault();
this.uploadFile(event.dataTransfer.files);
}

// At the drag drop area
// (dragover)=”onDragOverFile($event)”
onDragOverFile(event) {
event.stopPropagation();
event.preventDefault();
}

// At the file input element
// (change)=”selectFile($event)”
selectFile(event) {
this.uploadFile(event.target.files);
}

uploadFile(files: FileList) {
if (files.length == 0) {
console.log(“No file selected!”);
return

}
let file: File = files[0];

this.upload.uploadFile(this.appCfg.baseUrl + “/api/flash/upload”, file)
.subscribe(
event => {
if (event.type == HttpEventType.UploadProgress) {
const percentDone = Math.round(100 * event.loaded / event.total);
console.log(`File is ${percentDone}% loaded.`);
} else if (event instanceof HttpResponse) {
console.log(‘File is completely loaded!’);
}
},
(err) => {
console.log(“Upload Error:”, err);
}, () => {
console.log(“Upload done”);
}
)
}

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in