0

I need to send a multipart request to server with a file (document_example.pdf) and a json file that contains the data object (data_object_example.json) in Angular 7.

data_object_example.json -> { "attribute1": "name", "attribute2": "second_name" }

I know how create a multipart request, but I don't know how create json file by a object.

Thanks. ;)

Answer: Thanks to 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);
2
  • Why not just JSON.stringify() the data object and pass it as another field in the multipart request? Commented Mar 22, 2021 at 15:29
  • Hi, because I need to pass a File type json to server... and i can't change the backend. Commented Mar 22, 2021 at 15:33

1 Answer 1

3

In the case you can't change backend and must create a file from client-side. You can try this way:

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks this works! I've found another "easiest" way to do: const fileJson = new File([JSON.stringify(docJson)], "file.json", {type: "application/json'"});
Great that it could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.