如何将附加字段与 FormData 中的文件关联

jus*_*oob 6 javascript typescript angular

在我的 Web 应用程序中,我FormData从 Angular 前端发送到 Spring Boot 服务器。

我有以下Attachment模型:

export interface Attachment {
    file: File;
    comment: string;
}
Run Code Online (Sandbox Code Playgroud)

我想通过一个 发送多个附件FormData

目前我可以使用以下代码成功发送文件:

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
Run Code Online (Sandbox Code Playgroud)

但这不包括与文件一起的注释。

我还想以服务器可以准确识别哪个注释属于哪个文件的方式包含注释。

我不能简单地做类似的事情data.append('attachments', attachment),因为FormData只能有字符串和Blob值。

我能想到的最好的想法是将注释添加到FormData文件名作为键:

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);
}
Run Code Online (Sandbox Code Playgroud)

但这似乎不是一个好的解决方案,而且在后端解析起来也很麻烦。

有一个更好的方法吗?我真的很感激任何建议。