[英]Angular 7 Post file contents as multipart/form-data
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. ...其中我的字符串变量的内容可能是名为`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?您如何使用 Angular 7 和 HttpClient 服务获得这种效果? 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):
我没有要与之交互的实际 HTML 表单,我只有一些规定的二进制/字符串内容,我需要将其发布,就好像它是由看起来像的表单提交的一样(与 curl以上确实):
<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.我相信它可以实现,只是在执行正确的咒语时遇到了麻烦。
Use FormData
使用
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.在示例中,
this.logo
是一个File
对象。 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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.