Angular - POST上传文件

时间:2015-09-06 12:04:44

标签: angular typescript file-upload angular2-http

我使用AngularTypeScript将文件以及JSON数据发送到服务器。

以下是我的代码:

import {Component, View, NgFor, FORM_DIRECTIVES, FormBuilder, ControlGroup} from 'angular2/angular2';
import {Http, Response, Headers} from 'http/http';


@Component({ selector: 'file-upload' })
@View({
directives: [FORM_DIRECTIVES],
template: `
<h3>File Upload</h3>

<div>
     Select file:
    <input type="file" (change)="changeListener($event)">
</div>

`
})
export class FileUploadCmp {

public file: File;
public url: string;
headers: Headers;


constructor(public http: Http) {
    console.log('file upload Initialized');
    //set the header as multipart        
    this.headers = new Headers();
    this.headers.set('Content-Type', 'multipart/form-data');
    this.url = 'http://localhost:8080/test';
}

//onChange file listener
changeListener($event): void {
    this.postFile($event.target);
}

//send post file to server 
postFile(inputValue: any): void {

    var formData = new FormData();
    formData.append("name", "Name");
    formData.append("file",  inputValue.files[0]);

    this.http.post(this.url +,
      formData ,
        {
            headers: this.headers

        });
}

}

如何将formData转换为String并将其发送到服务器?我记得在AngularJS(v1)中你会使用transformRequest

5 个答案:

答案 0 :(得分:45)

查看我的代码,但请注意。我使用async / await,因为最新的Chrome测试版可以读取任何es6代码,这些代码由TypeScript通过编译获得。因此,您必须用gitlab.com替换asyns / await。

输入变更处理程序:

.then()

提交处理程序:

/**
 * @param fileInput
 */
public psdTemplateSelectionHandler (fileInput: any){
    let FileList: FileList = fileInput.target.files;

    for (let i = 0, length = FileList.length; i < length; i++) {
        this.psdTemplates.push(FileList.item(i));
    }

    this.progressBarVisibility = true;
}

FileUploadService。该服务还存储了正在上传进度$ property的内容,在其他地方,您可以订阅它并每500毫秒获得一个新值。

public async psdTemplateUploadHandler (): Promise<any> {
    let result: any;

    if (!this.psdTemplates.length) {
        return;
    }

    this.isSubmitted = true;

    this.fileUploadService.getObserver()
        .subscribe(progress => {
            this.uploadProgress = progress;
        });

    try {
        result = await this.fileUploadService.upload(this.uploadRoute, this.psdTemplates);
    } catch (error) {
        document.write(error)
    }

    if (!result['images']) {
        return;
    }

    this.saveUploadedTemplatesData(result['images']);
    this.redirectService.redirect(this.redirectRoute);
}

答案 1 :(得分:23)

查看此问题Github - Request/Upload progress handling via @angular/http,angular2 http尚不支持文件上传。

对于非常基本的文件上传,我创建了这样的服务功能作为解决方法(使用Тимофей's answer):

  uploadFile(file:File):Promise<MyEntity> {
    return new Promise((resolve, reject) => {

        let xhr:XMLHttpRequest = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(<MyEntity>JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        };

        xhr.open('POST', this.getServiceUrl(), true);

        let formData = new FormData();
        formData.append("file", file, file.name);
        xhr.send(formData);
    });
}

答案 2 :(得分:11)

您的http服务文件:

onChange(event) {
    let file = event.srcElement.files;
    let postData = {field1:"field1", field2:"field2"}; // Put your form data variable. This is only example.
    this._service.postWithFile(this.baseUrl + "add-update",postData,file).then(result => {
        console.log(result);
    });
}

调用您的函数(组件文件):

<input type="file" class="form-control" name="documents" (change)="onChange($event)" [(ngModel)]="stock.documents" #documents="ngModel">

您的HTML代码:

        sti.setJobKey(this.jobDetail.getKey());

答案 3 :(得分:4)

在我的项目中,我使用XMLHttpRequest发送multipart / form-data。 我认为它适合你。

uploader代码

let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.example.com/rest/api', true);
xhr.withCredentials = true;
xhr.send(formData);

以下是示例:https://github.com/wangzilong/angular2-multipartForm

答案 4 :(得分:2)

首先,您必须创建自己的内联TS-Class,因为目前不支持FormData类:

var data : {
  name: string;
  file: File;
} = {
  name: "Name",
  file: inputValue.files[0]
  };

然后使用JSON.stringify(data)

将其发送到服务器
let opts: RequestOptions = new RequestOptions();
opts.method = RequestMethods.Post;
opts.headers = headers;
this.http.post(url,JSON.stringify(data),opts);