在我的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);
}
但这似乎不是一个好的解决方案,并且在后端解析也很麻烦。
有更好的方法吗?我真的很感谢任何建议。