2016-07-26 19 views
1

Ich benutze Angular 2 mit Spring MVC. Ich habe derzeit eine Upload-Komponente, die einen AJAX-Aufruf an das Spring-Back-End sendet und eine Antwort von geparsten Daten aus einer CSV-Datei zurückgibt.Angular 2 Multipart AJAX Upload

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); 
} 
}); 
}; 
} 

Dies funktioniert, ich bekomme eine gültige Antwort zurück; Gibt es jedoch eine kantigere 2 Möglichkeit, diese Datei an Spring weiterzuleiten und eine Antwort zu erhalten? Ich habe mir in eine injizierbare Service Erstellung und Verwendung abonnieren, aber ich habe zu kämpfen worden, eine Antwort zurück

+0

prüft diese Antwort für ein Beispiel, wie eine Datei zum Hochladen http://stackoverflow.com/questions/32423348/angular2-post-uploaded-file –

Antwort

2

ich das tun schließlich erhalten folgende:

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); 
     }); 
    } 

} 

Ich kann dann injizieren eine Antwort in mein html wie:

<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> 

Dies hat Unterstützung für mehrere Datei-Uploads. Ich habe es als injizierbare Dienstleistung in diesem plunkr: https://plnkr.co/edit/wkydlC0dhDXxDuzyiDO3