Angular 7将文件内容作为多部分/表单数据发布 [英] 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
...,其中我的字符串变量的内容可能是本地文件"blob.bin"中的内容.我不确定该怎么做,但是 无效:
... 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)
如何使用Angular 7和HttpClient服务获得这种效果?我没有要与之交互的实际HTML表单,我只有一些规定的二进制/字符串内容,我需要发布,好像是由看起来像这样的表单提交的(与上面的卷曲相同):
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.
推荐答案
使用 FormData
const formData: FormData = new FormData();
formData.append('files', this.logo, this.logo.name);
this.http.post("upload", formData)
在示例中, this.logo
是一个 File
对象.您可以像这样从输入中获取文件对象:
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 />
并在组件文件中:
handleLogoFileInput(files: FileList) {
this.logo = files[0];
}
这篇关于Angular 7将文件内容作为多部分/表单数据发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!