Search code examples
javascriptangulartypescriptmultipartform-dataform-data

JavaScript - create a file out of json object and use it in a FormData


I'm trying to simulate a file upload by providing file content instead of serving the real file.

So - I'm doing something like this:

 uploadFile(jsonContent: string, otherParams: string) {

const formData = new FormData();
formData.append('jsonContent', data, 'fileName.json');
formData.append('deal_id', dealId);

return this.http.post(this.base_url + '/files', formData);}

I'm not seeing the content being sent to the API. Any advice? What I'm doing wrong?


Solution

  • Well, I've found a solution for this. In typescript you can create new File() and pass a blob object into it.

    Now u can actually create a file in your client side and send it as part as your FormData.

    here is the code:

        const st = JSON.stringify(json);
    
        const blob = new Blob([st], { type: 'application/json' });
    
        const file = new File([ blob ], 'FileName.json');
    
        const formData = new FormData();
        formData.append('file', file, 'FileName.json');
        formData.append('deal_id', dealId);