Angular 7 Post file contents as multipart/form-data

三世轮回 提交于 2021-01-27 14:19:46

问题


I have the content I want to POST available in a string variable. I want to use:

import { HttpClient } from '@angular/common/http'

... in order to accomplish the same effect as:

curl -F "image=@blob.bin" someurl.com

... where the contents of my string variable would be what might be in a local file called `blob.bin. I'm not sure how to do it, but this doesn't work:

this.http.post('http://someurl.com', fileContents)

How do you get this effect using Angular 7 and the HttpClient service? I don't have an actual HTML form that I'm interacting with, I just have some prescribed binary / string content that I need to post as though it was submitted by a form that looks like (which is the same as what the curl above does):

<form method='POST' action='http://someurl.com' enctype='multipart/form-data'>
  <input type='file' name='update'>
  <input type='submit' value='Update'>
</form>

I'm sure it can be achieved, just having trouble performing the right incantations.


回答1:


Use FormData

const formData: FormData = new FormData();
formData.append('files', this.logo, this.logo.name);
this.http.post("upload", formData)

In the example, this.logo is a File object. You can get the file object from your input like so:

<input (change)="handleLogoFileInput($event.target.files)" type="file" name="update />

and in the component file:

handleLogoFileInput(files: FileList) {
  this.logo = files[0];
}


来源:https://stackoverflow.com/questions/55754178/angular-7-post-file-contents-as-multipart-form-data

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