Angular 7 Post 文件内容为 multipart/form-data
Angular 7 Post file contents as multipart/form-data
我在字符串变量中提供了我想要 POST 的内容。
我想使用:
import { HttpClient } from '@angular/common/http'
...为了实现与以下相同的效果:
curl -F "image=@blob.bin" someurl.com
... 我的字符串变量的内容可能在名为 `blob.bin 的本地文件中。我不确定该怎么做,但是 没有 工作:
this.http.post('http://someurl.com', fileContents)
如何使用 Angular 7 和 HttpClient 服务获得这种效果?我没有正在与之交互的实际 HTML 表单,我只有一些规定的二进制/字符串内容需要 post 就像 它是由一个看起来像的表单提交的(与上面的 curl 所做的相同):
<form method='POST' action='http://someurl.com' enctype='multipart/form-data'>
<input type='file' name='update'>
<input type='submit' value='Update'>
</form>
我相信它可以实现,只是在执行正确的咒语时遇到了麻烦。
使用FormData
const formData: FormData = new FormData();
formData.append('files', this.logo, this.logo.name);
this.http.post("upload", formData)
在示例中,this.logo
是一个 File
对象。您可以像这样从输入中获取文件对象:
<input (change)="handleLogoFileInput($event.target.files)" type="file" name="update />
并且在组件文件中:
handleLogoFileInput(files: FileList) {
this.logo = files[0];
}
我在字符串变量中提供了我想要 POST 的内容。 我想使用:
import { HttpClient } from '@angular/common/http'
...为了实现与以下相同的效果:
curl -F "image=@blob.bin" someurl.com
... 我的字符串变量的内容可能在名为 `blob.bin 的本地文件中。我不确定该怎么做,但是 没有 工作:
this.http.post('http://someurl.com', fileContents)
如何使用 Angular 7 和 HttpClient 服务获得这种效果?我没有正在与之交互的实际 HTML 表单,我只有一些规定的二进制/字符串内容需要 post 就像 它是由一个看起来像的表单提交的(与上面的 curl 所做的相同):
<form method='POST' action='http://someurl.com' enctype='multipart/form-data'>
<input type='file' name='update'>
<input type='submit' value='Update'>
</form>
我相信它可以实现,只是在执行正确的咒语时遇到了麻烦。
使用FormData
const formData: FormData = new FormData();
formData.append('files', this.logo, this.logo.name);
this.http.post("upload", formData)
在示例中,this.logo
是一个 File
对象。您可以像这样从输入中获取文件对象:
<input (change)="handleLogoFileInput($event.target.files)" type="file" name="update />
并且在组件文件中:
handleLogoFileInput(files: FileList) {
this.logo = files[0];
}