Javascript 如何将其他字段与FormData中的文件关联
在我的web应用程序中,我将Javascript 如何将其他字段与FormData中的文件关联,javascript,angular,typescript,Javascript,Angular,Typescript,在我的web应用程序中,我将FormData从一个角度前端发送到Spring引导服务器 我有以下附件型号: export interface Attachment { file: File; comment: string; } 我想通过一个FormData发送多个附件 目前,我可以使用以下代码成功发送文件: attachments: Attachment[] = []; // pushing some data to the array const data = new
FormData
从一个角度前端发送到Spring引导服务器
我有以下附件
型号:
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
只能有string和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);
}
但这似乎不是一个好的解决方案,而且在后端解析也很麻烦
有更好的方法吗?我非常感谢您的建议。formdata可以保存键值对,发送多部分表单内容和常规字符串键值对是非常好的。@KunalMukherjee我的问题不是将多部分内容和常规键值对一起发送,而是以服务器可以明确识别文件注释对。@justanoob假设文件名是唯一的,也许您可以
data.append(`${attachment.file.name}@file`,attachment.file)
和data.append(`${attachment.file.name}@comment`,attachment.comment)
。服务器端您可以轻松重建更好的结构,以匹配以相同名称开头的注释和文件。您还可以对JSON进行字符串化并在服务器上解析:data.append('attachment',JSON.stringify(attachment))