Bhetzie Bhetzie - 4 months ago 53
Ajax Question

Angular 2 Multipart AJAX Upload

I'm using Angular 2 with Spring MVC. I currently have an Upload component that makes an AJAX call to the Spring backend and returns a response of parsed data from a .csv file.

export class UploadComponent {

uploadFile: function(){

var resp = this;

var data = $('input[type="file"]')[0].files[0];
this.fileupl = data;
var fd = new FormData();
fd.append("file", data);
$.ajax({
url: "uploadFile",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
resp.response = response;
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
}
});
};
}


This works, I get a valid response back; however, is there a more angular 2 way to pass this file to Spring and receive a response? I've been looking into creating an injectible service and using subscribe, but I've been struggling to get a response back

Answer

I ended up doing the following:

import { Component, Injectable } from '@angular/core';
import { Observable} from 'rxjs/Rx';
const URL = 'myuploadURL';

@Component({
  selector: 'upload',  
  templateUrl: 'upload.component.html',
  styleUrls: ['upload.component.css']
})

export class UploadComponent {

filetoUpload: Array<File>;
response: {};

constructor() {
  this.filetoUpload = [];
}

upload() {
        this.makeFileRequest(URL, [], this.filetoUpload).then((result) => {           
            this.response = result;            
        }, (error) => {
            console.error(error);
        });
    }
fileChangeEvent(fileInput: any){
        this.filetoUpload = <Array<File>> fileInput.target.files;
    }

    makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
        return new Promise((resolve, reject) => {
            let formData: any = new FormData();
            let xhr = new XMLHttpRequest();
            for(let i =0; i < files.length; i++) {
                formData.append("file", 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.open("POST", url, true);
            xhr.send(formData);
        });
    }

}

I can then inject a response into my html like:

<div class="input-group">
                <input type="file" id="file" name="file" placeholder="select file" (change)="fileChangeEvent($event)">

                <input type="submit" value="upload" (click)="upload()" class="btn btn-primary">
        </div>


    <div *ngIf="response">

    <div class="alert alert-success" role="alert">
    <strong>{{response.myResponseObjectProperty | number}}</strong> returned successfully!
    </div>

This has support for multiple file uploads. I created it as an injectable service in this plunkr: https://plnkr.co/edit/wkydlC0dhDXxDuzyiDO3

Comments