问题
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