问题描述
我试图在上传文件之前要求确认,因此服务器当前具有以下HTML代码:
<p-fileUpload mode="basic" name="file" url="{{urlUpload}}" chooseLabel="Upload CSV (onBeforeSend)="onBeforeSend($event)">
onBeforeSend (event): void {
const token = this.service.getTokenSession();
event.xhr.setRequestHeader('Authorization','Bearer ' + token);
this.confirmationService.confirm({
message: 'Are you sure to continue?',header : 'Confirmation',accept : () => {
this.service.showLoader();
this.onUpload(event);
},reject: () => {}
});
}
onUpload(event): void {
this.msgsPage = [];
try {
const response = JSON.parse(event.xhr.response);
console.log(response)
if (!response.ok) {
this.errorModalService.show('There was an error');
this.flagResultLoadErrors = true;
let c = 0;
for (let msg of response.map.errors) {
c++;
this.msgsPage.push({
detail : msg,severity: 'error',summary : 'Error ' + c,});
}
}
} catch (e) {
this.errorModalService.show('UnkNown error');
console.log(e)
} finally {
this.service.hideLoader();
}
}
有了这个,我试图阻止请求,但是没有发生,我得到的是文件在确认对话框之前发送到了服务器。
另外,当我尝试获取response
时遇到此错误:
SyntaxError: Unexpected end of JSON input
希望你能帮助我。
解决方法
您不能阻止该事件。这只是组件发出的事件。
https://github.com/primefaces/primeng/blob/master/src/app/components/fileupload/fileupload.ts#L367
您将需要使用自定义uploadHandler
。
<p-fileUpload name="myfile[]" customUpload="true" (uploadHandler)="myUploader($event)"></p-fileUpload>
myUploader(event) {
//event.files == files to upload
}
SyntaxError: Unexpected end of JSON input
这意味着您从xhr响应中获得的响应不是JSON,但是您正在尝试解析它。检查网络标签以查看服务器的响应是什么。