Javascript 如何在Angular中按对象为发送请求创建json文件

Javascript 如何在Angular中按对象为发送请求创建json文件,javascript,html,json,angular,typescript,Javascript,Html,Json,Angular,Typescript,我需要向服务器发送一个多部分请求,其中包含一个文件(document_example.pdf)和一个json文件,其中包含Angular 7中的数据对象(data_object_example.json) data\u object\u example.json->{ “属性1”:“名称”, “属性2”:“第二个名称” } 我知道如何创建多部分请求,但不知道如何通过对象创建json文件 谢谢 回答:感谢 在这种情况下,您无法更改后端,必须从客户端创建一个文件。 您可以这样尝试: const da

我需要向服务器发送一个多部分请求,其中包含一个文件(document_example.pdf)和一个json文件,其中包含Angular 7中的数据对象(data_object_example.json)

data\u object\u example.json->{ “属性1”:“名称”, “属性2”:“第二个名称” }

我知道如何创建多部分请求,但不知道如何通过对象创建json文件

谢谢

回答:感谢


在这种情况下,您无法更改后端,必须从客户端创建一个文件。 您可以这样尝试:

const data = {someKey: 'value'};
const blob = new Blob([JSON.stringify(data)], {type: 'text/plain'});
const tmpFile = new File([blob], 'data_object_example.json');

// now you can pass this tmp file to a form with your pdf
const form = new FormData();
form.append('file', tmpFile);

为什么不只是JSON.stringify()将数据对象作为另一个字段在多部分请求中传递?您好,因为我需要将文件类型JSON传递给服务器。。。我无法更改后端。嗨,谢谢,这很有效!我找到了另一种“最简单”的方法:
constfilejson=newfile([JSON.stringify(docJson)],“File.JSON”,{type:“application/JSON'”})很好,它可以帮助。
const data = {someKey: 'value'};
const blob = new Blob([JSON.stringify(data)], {type: 'text/plain'});
const tmpFile = new File([blob], 'data_object_example.json');

// now you can pass this tmp file to a form with your pdf
const form = new FormData();
form.append('file', tmpFile);