我在字符串变量中有我想要发布的内容。
我想使用:
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 表单,我只有一些规定的二进制/字符串内容,我需要将其发布,就好像它是由看起来像的表单提交的一样(与 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];
}
关于Angular 7 Post 文件内容作为 multipart/form-data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55754178/