向 PrimeNG FileUpload 数据传输添加附加信息

Add additional information to the PrimeNG FileUpload data transfer

我希望发送有关使用 primeng fileupload 组件上传的文件的附加信息。基本上,我需要知道这些上传的文件与什么有关。

我可以在 "onBeforeSend" 函数中添加 headers,就像下面示例中的授权代码一样。我在哪里可以添加其他信息,例如'DocumentID': 'A123'

onBeforeSend(event) {
    event.xhr.setRequestHeader("Authorization", 'Bearer ' + this.authService.getAccessToken());
} 

有人知道吗?

谢谢

primeng fileupload 控件的 onBeforeSend 事件中有一个名为 event.formData 的对象,您可以使用此对象来自定义带有附加信息的请求。我能够在当前正在进行的项目中成功实现此功能。

component.ts 文件中:

    onBeforeSend(event) {
       event.xhr.setRequestHeader("Authorization", `Bearer ${this.authService.getToken()}`);
       event.formData.append('DocumentID', 'A123');
    }

template.html 文件中:

    <p-fileUpload name="test[]" 
                  [url]="url_test" 
                  (onBeforeSend)="onBeforeSend($event)" 
                  accept="image/*" 
                  maxFileSize="5000000" 
                  withCredentials="true">

希望对您有所帮助!!

我将根据我的请求将实体与文件一起发送如下(有关详细信息,请参阅 this answer

我们可以FormData using the correct Content-Type 'application/json' 中的 Blob 中发送序列化为 JSON 的实体。有了这个我们可以包含嵌套对象,向我们的实体添加字段 - 我们将不必为每个新字段更改资源控制器方法签名 -

curso-update.component.ts

private onBeforeSend(event) {
    const token = this.localStorage.retrieve('authenticationToken') || this.sessionStorage.retrieve('authenticationToken');
    if (!!token) {
        event.xhr.setRequestHeader('Authorization', `Bearer  ${token}`);
    }
    event.formData.append('curso', new Blob([JSON.stringify(this.curso)], { type: 'application/json' }));
}

相应地更改资源控制器

CursoResource.java

@PostMapping("/cursos/archivos")
@Timed
public ResponseEntity<Curso> createCurso(@Valid @RequestPart(value = "curso") Curso curso, 

@RequestPart("archivos[]")MultipartFile[] archivos) {
...
Curso result = this.cursoService.save(curso);
...
}