0

Can anyone help me out with a plunker or reference on how uploading csv files in angular 2 are implemented?

2
  • 2
    this is about upload files by angular2.plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=preview Commented Feb 27, 2017 at 10:11
  • @Pengyy, it looks like this wouldn't work with my version of angular 2. i am getting some errors Commented Feb 27, 2017 at 10:52

3 Answers 3

1

here is a component you can reuse.

http://valor-software.com/ng2-file-upload/

You can install with

npm install ng2-file-upload --save

There is a backend example in express on the page.

Sign up to request clarification or add additional context in comments.

2 Comments

can i use my own php backend for the valor software?
yes of course. The component is independent of the backend.
0
HTML CODE:
-------------------------------------------------------------------------------
<div class="form-group">
<label for="fileChooseAFile">Choose a File</label>
<input id="fileChooseAFile" #data type="file" class="form-control" (change)="getFiles(data)" name="fileChooseAFile" accept=".csv">
</div>

<div class="col-md-12">
<div class="btn-bar">
<a href="#" class="btn btn-link">Cancel</a>
<a (click)="postfile();" class="btn btn-secondary">Upload</a>
</div>
</div>

-----------------------------------------------------------------------------
Component Code
-----------------------------------------------------------------------------
getFiles(files: any) {
        let taskExcelFiles: FileList = files.files;
        this.file = taskExcelFiles[0];
    }

postfile() {
        if (this.file !== undefined) {
       this._uploadService.postFormData(this.file)
            .map(response => {
                this.alertClosed = false;
            }).catch(error => this.errorMessage = <any>error);
            setTimeout(() => {
                this.alertClosed = true;
            }, 5000);
        } else {
            //show error
        }
    }

-----------------------------------------------------------------------
Service Code
-----------------------------------------------------------------------
postFormData(file: File) {
        return Observable.fromPromise(new Promise((resolve, reject) => {
            let formData: any = new FormData()
            let xhr = new XMLHttpRequest()

            formData.append("file", file, file.name);

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        resolve(xhr.response)
                    } else {
                        reject(xhr.response)
                    }
                }
            }
            xhr.open("POST", environment.baseUrl + '/uploadExcel', true);
            xhr.send(formData)
        }));
    }

1 Comment

can you create fiddle link
0

Angular 2+ provides good support for uploading file. No need for any third party library.

Here is my solution :

It is very important to leave the Content-Type empty. If you set the 'Content-Type' to 'multipart/form-data' the upload will not work !

upload.component.html

<input type="file" (change)="fileChange($event)" name="file" />

upload.component.ts

export class UploadComponent implements OnInit { constructor(public http: Http) {}

fileChange(event): void {
    const fileList: FileList = event.target.files;
    if (fileList.length > 0) {
        const file = fileList[0];

        const formData = new FormData();
        formData.append('file', file, file.name);

        const headers = new Headers();
        // It is very important le leave the Content-Type empty, if you set it to 'multipart/form-data' it will not work !
       // do not set headers.append('Content-Type', 'multipart/form-data');
        headers.append('Authorization', 'Bearer ' + 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9');
        const options = new RequestOptions({headers: headers});

        this.http.post('https://api.mysite.com/uploadfile', formData, options)
             .map(res => res.json())
             .catch(error => Observable.throw(error))
             .subscribe(
                 data => console.log('success'),
                 error => console.log(error)
             );
    }
}

}

1 Comment

can you create fiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.