如何将文件附加到formdata angular 2

时间:2017-07-20 05:15:12

标签: javascript angular file-upload form-data

我正在做一个文件上传组件。我需要提交一个formdata对象。由于某种原因,我无法将文件或任何内容附加到formdata对象。以下是我的代码;

import {Component, ElementRef,
        ViewChild,EventEmitter, Input, Output, OnInit, OnDestroy} from "@angular/core";
import { UploadService } from './file-upload.service';

@Component({
    selector: 'dbs-file-upload',
    template: `  <div class="file-upload-wrapper">
                    <dbs-input [(ngModel)]="fileName" type="text" class="input-long" placeholder='{{"upload.file_input_placeholder" | translate}}' readonly></dbs-input>
                    <button class="btn-browse" for="files">
                        <label for="files">Browse</label>
                        <input type="file" (change)="onChange($event)"
                                [multiple]="multiple"
                                id="files" style="visibility:hidden;"
                                accept=".csv, text/xml, application/xml, application/vnd.ms-excel"
                                #fileInput>
                        <img src="/images/ico_browse_plus.png">
                    </button>
                </div>`,
    styleUrls: ['./file-upload.component.scss'],
    providers: [UploadService]
})


export class FileUploadComponent implements OnInit{

    @Input() fileName: string;
    @Output() onSelect = new EventEmitter<any>();
    @Input() multiple: boolean = false;
    // @ViewChild('fileInput') inputEl: ElementRef;

    constructor(private service: UploadService) {
        // this.service.progress.subscribe(data => {
        //     // console.log(data);
        // })
    }

    ngOnInit() {

    }

    onChange(event) {
            var files = event.srcElement.files;
            console.log('filesss', files);
            if (files.length > 0) {
                let fd: FormData = new FormData();
                let xhr: XMLHttpRequest = new XMLHttpRequest();
                console.log(xhr, 'FAFAAJHAKB');
                for (let file of files) {
                    fd.append('files', file, file.name);
                }
                console.log(fd, 'FROM COMPAKAP');
            }
            this.fileName = files[0].name;
            this.onSelect.emit(files[0]);

            // this.service.makeFileRequest('http://localhost:8080/mock/upload-file-list.json', [], files).subscribe(() => {
            //     console.log('whyy why');
            // })
        }
}

我试图附加一个文件对象,当我在console.log时,formdata对象什么都不包含。在右边它应该至少得到附加的文件。谁能告诉我这里出了什么问题?提前致谢。我生命中第一次做文件上传代码。

1 个答案:

答案 0 :(得分:2)

在这里。

let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);
        let headers = new Headers();
        /** No need to include Content-Type in Angular 4 */
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        this.http.post(`${this.apiEndPoint}`, formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data => console.log('success'),
                error => console.log(error)
            )
    }
use this code inside onChange method