在 angular 8 中的一个请求中发送图像和 json 数据时出错

Error while sending image and json data in one request in angular 8

我正在尝试在一个 http post 请求中发送图像和一些 json 数据。 Header 是

this.httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
}

我的 html 部分是

<input #imageInput type="file" name="add-logo" accept="image/*"
    id="add-logo" (change)="onFileChanged(imageInput)" class="form-control cust-field" placeholder="">

和component.ts函数是

    logo:File
  onFileChanged(imageInput: any) {
      const file: File = imageInput.files[0];
      this.logo = file; 
}

错误是

HttpErrorResponse {headers: HttpHeaders, status: 422, statusText: "Unprocessable Entity", url: "myUrl", ok: false, …}
error:
messages: ["The logo field is required."]
status: false
__proto__: Object
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for url: 422 Unprocessable Entity"
name: "HttpErrorResponse"
ok: false
status: 422
statusText: "Unprocessable Entity"
url: "url"

我把这个object发给api

{first_name: "Firts Name", last_name: "Last Name", email: "a@gmail.com", phone: "+923045203200", password: "03045203200", …}
    accounting_method: "Cash"
    business_location: [{…}]
    business_location_name: "myLegalBusiness"
    business_name: "myLegalBusiness"
    business_phone: "0304520320055"
    business_system_name: "tradeName"
    confirm_p: "03045203200"
    currency: "ALL"
    currency_id: 1
    ein_ssn: "EIN34"
    email: "asad@gmail.com"
    first_name: "Firts Name"
    fy_end_month: "MARCH"
    last_name: "Last Name"
    logo: File {name: "users.png", lastModified: 1561615773639, lastModifiedDate: Thu Jun 27 2019 11:09:33 GMT+0500 (Pakistan Standard Time), webkitRelativePath: "", size: 2550, …}
    number_of_stores: 1
    password: "03045203200"
    phone: "+923045203200"
    store_name: "store"
    store_type: "Franchise"
    unique_code: "145dd" }

您可以使用 formData

onFileChanged(imageInput: any) {

  let fi = imageInput;

  if (fi.files && fi.files[0]) {

    let fileToUpload = fi.files[0];

    let formData: FormData = new FormData();

    formData.append("file", fileToUpload);

    formData.append('first_name', "Firts Name");
    formData.append('email', "a@gmail.com");
    formData.append('logo', {name: "users.png", lastModified: 1561615773639, lastModifiedDate: Thu Jun 27 2019 11:09:33 GMT+0500 (Pakistan Standard Time), webkitRelativePath: "", size: 2550, …});
    ...

    console.log(formData)

}

您正在尝试将不正确的实体或数据发送到图像属性中。在 angular 文件中,应使用

捕获事件

this.logo = imageInput.target.files[0]

这是针对所有情况的修改代码,请尝试使用它。如果你想要图像 link(文件路径)使用 imgLink 或者如果你要发送图像数据使用 imgData.Consider html 文件

<input type="file" (change)="selectFile($event)">

和 Ts 文件

imgLink         : any 
imgData         : any

selectFile(event) {

    this.imgLink = ''

    this.imgData  = event.target.files[0]

    //In your case
    this.logo = this.imgData

    let mimeType  = this.imgData.type

    if (mimeType.match(/image\/*/) == null) {
      const message = "This file type is not supported, Please upload in image format"
      return
    }

    let reader = new FileReader() 
    reader.readAsDataURL(this.imgData)
    reader.onload = (event) => { 
      this.imgLink = reader.result
    }
  }

您可以通过 'Content-Type': 'application/json' 发送图像。您必须更改 API 以接受 `'multipart/form-data'。那么只有你可以上传图片。

这是方法

const frmData = new FormData(); frmData.append("name", "name"); frmData.append("file","imageUrl");

const httpHeaders = new HttpHeaders({ "enctype": "multipart/form-data" });

const options = { headers: httpHeaders };

return this.http.post<string>( "/URL", frmData, options);