Reputation: 292
I have a requirement where admin user will upload .xlsx file which contains columns related to new user Name, Age, Gender.
On click of upload button, I need to post excel file to WEB API and save the data to SQL server.
I am using Angular 2, If anyone has an idea please let me know.
Thanks in advance.
Upvotes: 0
Views: 3021
Reputation: 159
You need to have an Injectable Service for file upload and then simply call it from component. Below is the code:
Service
import {Injectable, Inject} from '@angular/core';
import {Headers, Http, Response} from '@angular/http';
import { Subject } from 'rxjs/Subject';
import {Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class FileUploadService {
fileUpload(url: string, files: File[])
: Promise<any> {
progress$: any;
progressObserver: any;
progress: any;
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("FileUpload", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
}
Component
constructor(private fileUploadService: FileUploadService) {
}
this.fileUploadService.fileUpload(this.postURL,this.files)
.then(dcDetailResponse => this.resetForm(dcDetailResponse))
.catch(error => console.log(error));
then at API controller(c#), change it as per your needs:
[HttpPost]
public IHttpActionResult UploadDCDetail()
{
if (HttpContext.Current.Request.Files.Count > 0)
{
}
}
Hope it helps!
Upvotes: 1