也一直试图弄清楚这一点,文档确实没有太大帮助。这是我最终使用的
如下创建了一个组件。路径输入表示已在文件服务上创建的文件夹。如果文件夹不存在,代码仍然需要重构以创建文件夹,但到目前为止它仍然有效。
import { Component, ElementRef, Input, ViewChild } from '@angular/core';
import { Headers, Http } from '@angular/http';
import * as constants from '../shared/config';
@Component({
selector: 'file-upload',
template: '<input type="file" #fileInput>'
})
export class FileUploadComponent {
@Input() multiple: boolean = false;
@Input() path: string = '';
@ViewChild('fileInput') inputEl: ElementRef;
baseResourceUrl: string = constants.API_BASE_URL + '/api/v2/files/';
constructor(private http: Http) {}
upload() {
console.log("changed");
let inputEl: HTMLInputElement = this.inputEl.nativeElement;
let fileCount: number = inputEl.files.length;
let fileName: string = '';
console.log(inputEl.files);
let formData = new FormData();
if (fileCount > 0) { // a file was selected
formData.append('files[]', inputEl.files.item(0), inputEl.files.item(0).name);
formData.append('pmCase', '100');
fileName = inputEl.files.item(0).name;
let myHeader = new Headers();
let token = localStorage.getItem('session_token');
myHeader.append('Content-Type', 'multipart/form-data');
myHeader.append('X-Dreamfactory-API-Key', 'xxxxxxxxxxx');
myHeader.append('X-Dreamfactory-Session-Token', token);
this.http
.post(`${this.baseResourceUrl + this.path + fileName}`, formData, { headers: myHeader })
.map((resp) => resp.json())
.subscribe((uploadResp) => {
console.log(uploadResp);
}, (error) => console.error(error));
}
}
}