我希望发送其他信息,其中包含使用 primeng 文件上传组件上传的文件。基本上,我需要知道这些上传的文件与什么相关。
我可以在"onBeforeSend"函数中添加标头,例如下面的授权代码。 我在哪里可以添加其他信息,例如"文档ID":"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">
希望对您有所帮助!!
我根据我的请求将实体与文件一起发送,如下所示(有关更多信息,请参阅此答案(
我们可以使用正确的内容类型"application/json"在 FormData 中的 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);
...
}