尝试以角度4形式上传文件时验证文件类型的最佳方法是什么。有没有简单的方法来实现这个目标?
答案 0 :(得分:0)
是的,您可以从客户端验证
示例代码
upload(event: any) {
let files = event.target.files;
//check file is valid
if (!this.validateFile(files[0].name)) {
console.log('Selected file format is not supported');
return false;
}
let fData: FormData = new FormData;
for (var i = 0; i < files.length; i++) {
fData.append("file", files[i]);
}
var _data = {
filename: 'Sample File',
id: '0001'
}
fData.append("data", JSON.stringify(_data));
this._service.uploadFile(fData).subscribe(
response => console.log(response),
error => console.log(error)
)
}
验证
validateFile(name: String) {
var ext = name.substring(name.lastIndexOf('.') + 1);
if (ext.toLowerCase() == 'war') {
return true;
}
else {
return false;
}
}