如何将附加字段与FormData中的File相关联

时间:2019-01-09 12:14:01

标签: javascript angular typescript

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

我有以下Attachment模型:

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

我想通过一个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

但这不包括注释以及文件。

我还希望以一种方式包含注释,以便服务器可以准确识别出哪个注释属于哪个文件。

我不能简单地做类似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);
}

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

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

0 个答案:

没有答案