11

I'm looking to send additional information with files that are being uploaded with the primeng fileupload component. Basically, I need to know what these uploaded files are relevant to.

I can add headers in the "onBeforeSend" function like the Authorization code as in the example below. Where could I add additional information e.g. 'DocumentID': 'A123'

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

Anyone know?

Thanks

thegunner
  • 6,883
  • 30
  • 94
  • 143

2 Answers2

7

In onBeforeSend event of primeng fileupload control there is an object called event.formData, you can use this object to customize the request with aditional information. I was able to implement this functionality successfully in current project i'm working on.

In component.ts file:

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

In template.html file:

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

Hope it helps!!

JuanDM
  • 1,250
  • 10
  • 24
0

I'm sending the entity alongside the files on my request as follows (see this answer for more info)

We can send the Entity serialized as JSON in a Blob inside our FormData using the correct Content-Type 'application/json'. With this we can include nested objects, add fields to our Entity -and we won't have to change the Resource Controller method signature with every new field-

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' }));
}

change the Resource Controller accordingly

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);
...
}
cirovladimir
  • 593
  • 6
  • 25