【问题标题】:How create json file by object for send request in Angular如何按对象创建json文件以在Angular中发送请求
【发布时间】:2021-03-23 22:54:25
【问题描述】:

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

data_object_example.json -> { “属性1”:“名称”, “属性 2”:“第二个名称” }

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

谢谢。 ;)

回答:感谢HaiTH

const docJson = {
  fileDocType: file.name.split('?')[0].split('.').pop(),
  fileName: file.name
}
const fileJson = new File([JSON.stringify(docJson)], "file.json", {type: "application/json'"});

const formData = new FormData();
formData.append('json', fileJson);

【问题讨论】:

  • 为什么不只是 JSON.stringify() 数据对象并将其作为多部分请求中的另一个字段传递?
  • 您好,因为我需要将文件类型 json 传递给服务器...而且我无法更改后端。

标签: javascript html json angular typescript


【解决方案1】:

如果您无法更改后端并且必须从客户端创建文件。 你可以这样试试:

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);

【讨论】:

  • 嗨,谢谢这个作品!我找到了另一种“最简单”的方法:const fileJson = new File([JSON.stringify(docJson)], "file.json", {type: "application/json'"});
  • 能帮上忙真是太好了。
猜你喜欢
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 2019-12-21
  • 1970-01-01
  • 2019-09-17
  • 1970-01-01
相关资源
最近更新 更多