最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Jun 11, 2018 at 6:05 Eliran Eliassy asked Jun 10, 2018 at 13:49 Eliran EliassyEliran Eliassy 1,60012 silver badges25 bronze badges 2
  • can I see your data variable value in formData.append('jsonContent', data, 'fileName.json');? – wobsoriano Commented Jun 11, 2018 at 6:13
  • @sorxrob it's just a js object... {name: 'foo'} – Eliran Eliassy Commented Jun 12, 2018 at 8:22
Add a ment  | 

2 Answers 2

Reset to default 5

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

Try to add this in your headers

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

this.http.post(this.base_url + '/files', formData, headers)
发布评论

评论列表(0)

  1. 暂无评论