我会使用upload component在Angular上传文件
这是我的HTML:
<p-fileUpload mode="basic" name="demo[]" customUpload="true" accept="image/*" maxFileSize="1000000" (uploadHandler)="upload($event)"></p-fileUpload>
在我的ts中我打印参数值
upload(event) {
console.log(event)
}
我只获得元数据而不是blob内容
{"files":[{"objectURL":{"changingThisBreaksApplicationSecurity":"blob:https://prime-ng-file-uploading.stackblitz.io/d429e761-c391-45fa-8628-39b603e25225"}}]}
我还会通过API将文件内容发送到服务器
在官方文档中,您有一个示例:
export class FileUploadDemo {
uploadedFiles: any[] = [];
constructor(private messageService: MessageService) {}
onUpload(event) {
for (let file of event.files) {
this.uploadedFiles.push(file);
}
this.messageService.add({
severity: 'info',
summary: 'File Uploaded',
detail: ''
});
}
}
当我使用primeNG
时,我这样做(仅上传1个文件):
HTML
<p-fileUpload name="myfile[]" customUpload="true" multiple="multiple" (uploadHandler)="onUpload($event)" accept="application/pdf"></p-fileUpload>
component.ts
export class AlteracionFormComponent {
uplo: File;
constructor(private fileService: FileUploadClientService) {}
onUpload(event) {
for (let file of event.files) {
this.uplo = file;
}
this.uploadFileToActivity();
}
uploadFileToActivity() {
this.fileService.postFile(this.uplo).subscribe(data => {
alert('Success');
}, error => {
console.log(error);
});
}
}
我的服务(在Angular
)
service.ts
postFile(id_alteracion: string, filesToUpload: FileUploadModel[], catalogacion: any): Observable<any> {
let url = urlAPIAlteraciones + '/';
url += id_alteracion + '/documentos';
const formData: FormData = new FormData();
formData.append('json', JSON.stringify(catalogacion));
for (let file of filesToUpload) {
formData.append('documento', file.data, file.data.name);
}
console.log(formData);
let headers = new HttpHeaders();
return this._http.post(url, formData, { headers: headers });
}
希望有所帮助