Angular 2 Multipart AJAX上传

时间:2016-07-26 02:47:04

标签: ajax spring-mvc post typescript angular

我在Spring MVC中使用Angular 2。我目前有一个上传组件,它对Spring后端进行AJAX调用,并返回来自.csv文件的已解析数据的响应。

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

这有效,我得到了有效回复;但是,有一个更有棱角的2种方法将此文件传递给Spring并收到响应吗?我一直在寻求创建一个可注意的服务和使用订阅,但我一直在努力获得回复

1 个答案:

答案 0 :(得分:2)

我最终做了以下事情:

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

}

然后我可以在我的html中注入一个响应,如:

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

这支持多个文件上传。我在这个plunkr中创建了它作为注射服务: https://plnkr.co/edit/wkydlC0dhDXxDuzyiDO3