Angular2文件上传

来源:互联网 发布:淘宝 延长收货使用规则 编辑:程序博客网 时间:2024/05/29 11:09

xxx.module.ts模块
import { NgModule} from “@angular/core”;
import { FileUploadModule } from “ng2-file-upload” ;
import { XXXComponent } from “./xxx.component”;

@NgModule({
imports:[
FileUploadModule
],
declarations:[
XXXComponent ,/component,pipe,directive/],
providers:[]
})
export class XXXModule{}

xxx.component.ts组件
import { Component} from “@angular/core”;
import { FileUploader} from “ng2-file-upload/file-upload/file-uploader.class”;

@Component({
templateUrl:’xxx.component.html’
})

export class XXXComponent{
constructor(){ }
public fileList;
public uploadFile(event){
this.fileList = event.target.files;
}

//上传
public submitUploadFile(){
if(this.fileList.length>0){
let file:File = this.fileList[0];
let formData = new FormData();
formData.append(‘file’,file,file.name);
let headers = new Headers();
headers.append(‘Accept’,’application/json’);
let options = new RequestOptions({headers:headers});
this.http.post(url,formData,options)
.map(res=>res.json())
.catch(error=>Observable.throw(error))
.subscribe(

//返回上传数据
//success or fail
)

}
}
}

xxx.component.html
这里写图片描述

原创粉丝点击