2

I want to save a JSON file to the server using fetch() API in Javascript. The idea is to save a data blob to a folder in the served named data.

Here's my code:

function project_save_confirmed(input) {
    if ( input.project_name.value !== _onco_settings.project.name ) {
        project_set_name(input.project_name.value);
    }

    // onco project
    var _onco_project = { '_onco_settings': _onco_settings,
        '_onco_img_metadata': _onco_img_metadata,
        '_onco_attributes': _onco_attributes };

    var filename = input.project_name.value + '.json';
    var data_blob = new Blob( [JSON.stringify(_onco_project)],
        {type: 'text/json;charset=utf-8'});

    //save_data_to_local_file(data_blob, filename);
    upload_json_to_server(data_blob, filename);

    user_input_default_cancel_handler();
}

async function upload_json_to_server(data_blob, filename) {
    const response = await fetch('https://localhost:3000/api/json', {
        method: 'POST',
        body: data_blob,
        headers: {
            'Content-Type': 'text/json'
        }
    });
    const myJson = await response.json();
    console.log(myJson);
}

I pass the JSON data blob to the upload function and then I want to make a POST API call to save that data blob to disk and save it as filename.json.

I guess I'm failing on the Content Type. Is there anything like 'Content-Type': 'file/json'?

Kind regards

Luís Costa
  • 1,183
  • 15
  • 33
  • 1
    Possible duplicate of [What is the correct JSON content type?](https://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type) –  Dec 15 '18 at 03:54
  • I was just looking to that thread. I don't think the OP means a JSON blob file but JSON text. – Luís Costa Dec 15 '18 at 03:56
  • What’s the difference? And do you mean “blob”? – Ry- Dec 15 '18 at 03:58
  • Yes, blob. Thank you. I want to save the file already encoded and not the JSON text in it. I'm not sure I'm understanding, sorry – Luís Costa Dec 15 '18 at 03:59
  • 1
    Try answer of [How can javascript upload a blob?](https://stackoverflow.com/questions/13333378/how-can-javascript-upload-a-blob), where they use the FormData API and set the jQuery.ajax's `processData` and `contentType` to `false`. – KeitelDOG Dec 15 '18 at 04:50

0 Answers0