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

我只是一个虾纸丫 提交于 2020-04-18 06:26:09

问题


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?


回答1:


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



回答2:


Try to add this in your headers

const headers = {
  processData: false,
  contentType: false 
}

this.http.post(this.base_url + '/files', formData, headers)


来源:https://stackoverflow.com/questions/50784370/javascript-create-a-file-out-of-json-object-and-use-it-in-a-formdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!