简体   繁体   English

Angular 7 Post 文件内容作为 multipart/form-data

[英]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.

相关问题 Angular HttpClient发布两个文件(Multipart / form-data) - Angular HttpClient Post Two Files (Multipart/form-data) 无法 POST 请求多部分/表单数据角度 - Cannot POST request multipart/form-data angular 如何将多部分/表单数据从 Angular 发布到 Nodejs Multer? - How to post multipart/form-data from Angular to Nodejs Multer? 在Angular2中构建multipart / form-data POST请求并验证输入类型File - Build multipart/form-data POST request in Angular2 and validate Input type File 将多部分/表单数据发布到端点 - Post multipart/form-data to endpoint 如何发送多部分/表单数据文件? - How to send multipart/form-data file? 如何从角度发布多部分/表单数据到Django REST API - How to post multipart/form-data from angular to Django REST API Angular 8,上传(使用post multipart/form-data)FileReader.readAsDataURL的结果 - Angular 8, upload (using post multipart/form-data) the result of FileReader.readAsDataURL Angular 5-如何将null设置为HTTP POST multipart / form-data的内容类型 - Angular 5 - How to set null as content type for HTTP POST multipart/form-data 使用ngx-mat-file-input从Angular上载文件作为多部分/表单数据 - Upload File as multipart/form-data from Angular with ngx-mat-file-input
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM