无论选项设置如何,Angular2 Multipart /表格数据都以普通/文本形式发送

时间:2017-07-03 09:55:51

标签: angular client

我尝试将数据从客户端发送到我的服务器multipart/form-data,但服务器始终以纯文本形式接收数据。这是我的代码:

   import { Component, ElementRef, ViewChild, Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';

@Component({
    moduleId: module.id,
    selector: 'file-upload',
    templateUrl: 'upload.component.html',
})

@Injectable()
export class FileUploadComponent {
    @ViewChild('upload-btn') uploadbtn: any;
    @ViewChild('inputFile') inputFile: ElementRef;
    @ViewChild('progressBar') progressBar: any;

    constructor(private http: Http, private e1: ElementRef) { }

    /* When button is clicked open input */
    upload() {
        console.log("clicked");
        this.inputFile.nativeElement.click();
    } // end of upload

    /* Process input form */
    sendToServer() {
        // Get form input
        let inputFile: HTMLInputElement = this.inputFile.nativeElement;
        let formData = new FormData();
        let fileCount: number = inputFile.files.length;
        let headers = new Headers();
        headers.append('enctype', 'multipart/form-data');
        let options = new RequestOptions({ headers: headers });
        console.log(formData);
        console.log(options);
        console.log(headers);


        console.log("File Count: " + fileCount);

        if (fileCount > 0) {
            for (let i = 0; i < fileCount; i++) {
                console.log("Count: " + i);
                formData.append('uploads[]', inputFile.files.item(i), 
    inputFile.files.item(i).name);
            }


            this.http.post('server IP', formData, options)
            .subscribe(data => console.log("Upload Success!")); 

        }

} // end of send to server

}

我的服务器是IIS,正在接收来自angular2前端的帖子请求。

1 个答案:

答案 0 :(得分:0)

当您将文件从角度发送到后端时,您应该按以下方式发送:

makeFileRequest (params: string[], files: File[], employee:Employee, 
  doctype:string){
  return Observable.create(observer => {
    let formData: FormData = new FormData(),
        xhr: XMLHttpRequest = new XMLHttpRequest();

    formData.append("file", files[0]);
    formData.append("type", doctype);
    formData.append("employeeid", employee.id.toString());
    let token = localStorage.getItem('jwtToken');

    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              //  observer.next(JSON.parse(xhr.response));
              console.log(xhr.response);
              observer.next();
                observer.complete();
            } else {
                observer.error(xhr.response);
            }
        }
    };

    xhr.upload.onprogress = (event) => {
        this.progress$ = Math.round(event.loaded / event.total * 100);
        this.progressObserver.next(this.progress$);
    };
    let url = "http://localhost:8080/docapi/documents/upload";
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Authorization', token );
    xhr.send(formData);
});
}

以下是component.ts相关函数:

 updateFile(event){
   this.files = event.srcElement.files;
}
upload() {
   console.log('onChange');
   console.log(this.doctype);
this.employeeService.makeFileRequest( [], this.files, this.employee, this.doctype).subscribe(response => {
  console.log('sent');
  console.log(response);
});

}

我认为现在还不支持发送它,因为你发送了一个简单的帖子。您必须执行XMLHttpRequest并通过它发送文件。

最后,希望这有帮助。