JavaScript-从json对象创建文件并在FormData中使用它 [英] JavaScript - create a file out of json object and use it in a FormData
本文介绍了JavaScript-从json对象创建文件并在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);}
我没有看到内容被发送到API. 有什么建议吗?我在做什么错了?
I'm not seeing the content being sent to the API. Any advice? What I'm doing wrong?
推荐答案
好吧,我已经找到了解决方案.
在打字稿中,您可以创建new File()
并将一个blob对象传递给它.
Well, I've found a solution for this.
In typescript you can create new File()
and pass a blob object into it.
现在,您实际上可以在客户端创建一个文件,并将其作为FormData的一部分发送.
Now u can actually create a file in your client side and send it as part as your FormData.
下面是代码:
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);
这篇关于JavaScript-从json对象创建文件并在FormData中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文