How to associate additional field with File in FormData

Viewed 188

In my web application i'm sending FormData from an Angular front-end to a Spring Boot server.

I have the following Attachment model:

export interface Attachment {
    file: File;
    comment: string;
}

I would like to send multiple attachments through one FormData.

Currently i can send the files successfully with the following code:

attachments: Attachment[] = [];

// pushing some data to the array

const data = new FormData();
for (const attachment of this.attachments) {
      data.append('attachments', attachment.file);
}

// POSTing data to the server

But this doesn't include the comments along with the files.

I would like to include the comments as well in a way that the server could identify exactly which comment belongs to which file.

I cannot simply do something like data.append('attachments', attachment), because FormData can only have string and Blob values.

The best idea i could come up with is to add the comments to the FormData with the file names as the keys:

for (const attachment of this.attachments) {
      data.append('attachments', attachment.file);

      // the key is the file name and the value is the comment
      data.append(attachment.file.name, attachment.comment);
}

But this doesn't seem like a good solution and it's cumbersome to parse on the backend as well.

Is there a better way to do this? I'd really appreciate any advice.

0 Answers
Related