如何使用ng2-file-upload + angular 2获取文件对象

时间:2017-05-18 09:44:47

标签: angular angular2-directives angular-file-upload ng2-file-upload

我想完成上传文件拖动: 我正在使用ng2-file-upload版本1.2.1以及以下代码片段:

app.module.ts:

import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload';
..
imports: [
        FileUploadModule
]

component.ts:

import { FileUploader } from 'ng2-file-upload/ng2-file-upload';

...

class AppXYZComponent{
private uploader: FileUploader = new FileUploader({ url: 'blah.com' });

    public hasBaseDropZoneOver:boolean = false;
    //public hasAnotherDropZoneOver:boolean = false;

    public fileOverBase(e:any):void {
        console.log("hasBaseDropZoneOver", e);
        this.hasBaseDropZoneOver = e;
    }
}

app.component.html:

<div class="well" ng2FileDrop [uploader]="uploader" [ngClass]="{'another-file-over-class': hasBaseDropZoneOver}"
             (fileOver)="fileOverBase($event)"
             >
            Drop CSV here
        </div>

函数fileOverBase在拖动时成功调用,事件e打印为true。现在我如何获得拖动文件的对象??

2 个答案:

答案 0 :(得分:6)

你需要使用afterAddingfile方法来获取ng2-file-upload插件中的文件对象。

import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
...

class AppXYZComponent{
public uploader: FileUploader;
public hasBaseDropZoneOver:boolean = false;
//public hasAnotherDropZoneOver:boolean = false;

constructor(){
   this.uploader = new FileUploader({ url: 'blah.com' });
   this.uploader.onAfterAddingFile = (fileItem) => {
                fileItem.withCredentials = false;
                console.log(fileItem); // fileItem is the file object
            };
}
 public fileOverBase(e:any):void {
    console.log("hasBaseDropZoneOver", e);
    this.hasBaseDropZoneOver = e;
  }
}

答案 1 :(得分:1)

我知道其迟到的回复,但可能对其他人有帮助

更改app.component.html:**代码

<div class="well" ng2FileDrop [uploader]="uploader" [ngClass]="{'another-file-over-class': hasBaseDropZoneOver}"
         (fileOver)="fileOverBase($event)" **(onFileDrop)="onFileDrop($event)"**
         >
        Drop CSV here
    </div>

更改component.ts:如下**代码

class AppXYZComponent{
private uploader: FileUploader = new FileUploader({ url: 'blah.com' });

public hasBaseDropZoneOver:boolean = false;
//public hasAnotherDropZoneOver:boolean = false;

public fileOverBase(e:any):void {
    console.log("hasBaseDropZoneOver", e);
    this.hasBaseDropZoneOver = e;
}

**public onFileDrop(fileList: File[]) {
    console.log(fileList);// u get file as fileList[0]
}**
}