简体   繁体   English

如何使用http POST请求作为formData发送文件?

[英]How can I send a file using http POST request as a formData?

I'm using swagger 2.0 to document my API. 我正在使用swagger 2.0来记录我的API。 I defined a resource /getsize as shows the next code snippet: 我定义了一个资源/ getsize,如下面的代码片段所示:

    post:
      operationId: users.getSize
      tags:
        - Users
      summary: Measure your body
      description: import a photo
      consumes:
         - multipart/form-data
      parameters:
        - in: formData
          name: image1
          type: file
          required: true
        - in: path
          name: height
          type: number
          required: true

When I try to send the request from the sawgger ui I get the expected result. 当我尝试从sawgger ui发送请求时,得到了预期的结果。 But, the problem occurs when I try to access this resource using angluar component, here a code snippet of the component.ts file: 但是,当我尝试使用Angluar组件访问此资源时,就会出现问题,这里是component.ts文件的代码片段:

onSubmit() {
    const formData = new FormData();
    formData.append('image1', this.image);
    console.log(formData.getAll);
    console.log(this.image);
    this.http.post(endpoint,formData);
    .subscribe(res => {
        console.log(res);
        alert('SUCCESS !!');
      })
}

The server response is: 服务器响应为:

error:
detail: "Missing formdata parameter 'image1'"
status: 400
title: "Bad Request"
type: "about:blank"

Any suggestions ? 有什么建议么 ?

You can do this using URLSearchParams as the body of the request and angular will automatically set the content type to application/x-www-form-urlencoded and encode the body properly. 您可以使用URLSearchParams作为请求的主体来执行此操作,angular会自动将内容类型设置为application / x-www-form-urlencoded并对主体进行正确编码。

This post explained the answer in detail 这篇文章详细解释了答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在一篇http帖子中发送FormData和一个对象? - How can I send FormData and an object in one http post? 如何在 Angular 8 中使用 FormData 发送 http 请求? - How to send http request using FormData in Angular 8? 无法使用发布请求发送表单数据 - Cannot send formdata using post request 无法在角度7中使用FormData使用Ajax发送文件 - Can not send a file with Ajax using FormData in angular 7 如何使用来自@ angular / http的http发送帖子请求 - how to send post request using http from @angular/http 如何使用 http 客户端发布方法从 angular 发送此 json 请求正文? - How do I send this json request body from angular using http client post method? 如何使用打字稿通过参数发送 HTTP POST REQUEST - How to send a HTTP POST REQUEST by parameters using typescript 我应该如何在Http POST请求的主体中发送图像文件以及其他形式的角度数据5。后端在Laravel中使用Intervention包 - How shall I send an image file in body of Http POST request in along with other form data angular 5. Backend is using Intervention package in Laravel 如何使用 Node/Multer 在 post 请求上捕获 FormData - How to capture FormData on a post request using Node/Multer 我无法使用 ```http.post``` 发送数据 - I can't send data using ```http.post```
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM