Angular2使用ng2-file-upload上传文件,Angular2中有两个比较好用的上传文件的第三方库,一个是ng2-file-upload,一个是ng2-uploader。ng2-uploader是一个轻便的上传文件的支持库,功能较弱,而ng2-file-upload是一个功能比较全面的上传文件的支持库。这里主要介绍一下ng2-file-upload的使用。
1 下载相关模块
进入到项目根目录执行 npm install ng2-file-upload --save
坑01:有时候利用npm下载不成功
2 在主模块中导入上传模块
技巧01:一般都是在共享模块中导入再导出,然后在需要的模块中导入共享模块就可以啦
3 编写上传文件组件
import { Component, OnInit } from '@angular/core';
import {FileUploader} from 'ng2-file-upload';
@Component({
selector: 'app-test-upload-file',
templateUrl: './test-upload-file.component.html',
styleUrls: ['./test-upload-file.component.css']
})
export class TestUploadFileComponent implements OnInit {
private uploader: FileUploader = new FileUploader({
url: '/devProject/uploadClient',
method: 'POST',
itemAlias: 'file'
});
constructor() { }
ngOnInit() {
}
/**
* 上传文件内容变化时执行的方法
* @param event
*/
selectedFileOnChanged(event: any) {
// 这里是文件选择完成后的操作处理
// alert('上传文件改变啦');
console.log(event.target.value);
console.log(event);
}
/**
* 上传文件方法
*/
uploadFile() {
alert('执行上传文件');
// 上传
this.uploader.queue[0].onSuccess = function (response, status, headers) {
// 上传文件成功
if (status == 200) {
// 上传文件后获取服务器返回的数据
const tempRes = response;
alert(response);
} else {
// 上传文件后获取服务器返回的数据错误
alert('上传失败');
}
};
// onSuccessItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any;
this.uploader.queue[0].upload(); // 开始上传
// this.uploader.queue[0].onSuccess()
alert('上传之后');
}
}