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