本文介绍了使用HttpClient上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用angular的到API 内容类型:multipart / form-data (angular v4 +) 。是否支持?怎么做?

I try to upload an image with angular's HttpClient to API Content-Type: multipart/form-data (angular v4+). Is it supported? How to do it?

当使用像。我更喜欢使用带有 HttpClient 的自定义方法,我可以将其与其他访问API的方法一起放入http服务。

The upload works with XMLHttpRequest when using module like ng2-fancy-image-uploader. I would prefer to use a custom method with HttpClient which i could put into a http service together with other methods for accessing API.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class ModelService {
  constructor(private http: HttpClient) { }

  public async updateAvatar(file: File): Promise<void> {

    // headers
    const headers = new HttpHeaders()
      .append('Content-Type', 'multipart/form-data');

    const formData: FormData = new FormData();
    formData.append('avatar', file, file.name);

    const response: HttpResponse = await this.http
      .patch('https://example.com/avatar', formData, { headers, observe: 'response' })
      .toPromise();

    console.log(response.status);
  }
}



avatar-uploader.component.ts



avatar-uploader.component.ts

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ModelService } from './path/to/model.service';

@Component({
  selector: 'app-avatar-uploader',
  template: '<input type="file" #fileInput (changes)="uploadAvatar()">'
})
export class AvatarUploaderComponent implements OnInit {

  @ViewChild('fileInput') fileInputElement: ElementRef;

  constructor() { }

  ngOnInit() { }

  public async uploadAvatar() {
    const file: File = this.fileInputElement.nativeElement.files[0];

    await this.model.updateAvatar(file);
  }

}

此版本向(发送请求) express)但是 multer (用于解析 multipart / form-data 请求的库)无法解析请求。

This version sends a request to (express) API, but multer (a library for parsing multipart/form-data requests) fails to parse the request.

所以我想我要么错误地使用 HttpClient ,要么它不支持 multipart / form-data requests。

So i guess i either use the HttpClient incorrectly, or it doesn't support multipart/form-data requests.

我想有人可以发送base64编码文件或使用 XmlHttpRequest ,但我特别询问 HttpClient 的能力。

I guess one could send base64 encoded file or use XmlHttpRequest, but i ask specifically about HttpClient's ability to do it.

推荐答案

对我而言,诀窍不是将content-type设置为multipart / form-data。但这是我自动完成的。

For me the trick was not to set the content-type to multipart/form-data. But that was done automatically for me.

<label>
  <input type="file" (change)="setFiles($event)" style="display:none" multiple/>
  <a mat-raised-button color="primary">
    <mat-icon>file_upload</mat-icon>
    Select Documents
  </a>
</label>

这是我上传multipart / form-data的代码。无需设置标题。

Here's my code that uploads multipart/form-data. No need to set the headers.

private setFile(event) {
    let files = event.srcElement.files
    if (!files) {
      return
    }

    let path = `${environment.celoApiEndpoint}/api/patientFiles`
    let data = {"patientData": {
      "uid": "",
      "firstName": "",
      "lastName": "",
      "gender": "Not Specified",
      "dateOfBirth": ""
    }}
    // let headers = new HttpHeaders()
    //   .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW')
    // let headers = new HttpHeaders().set('content-type', 'multipart/form-data')
    const formData: FormData = new FormData();

    for (let i = 0; i < files.length; i++) {
      formData.append(i.toString(), files[i], files[i].name);
    }
    formData.append("data", JSON.stringify(data));
    this.http.post(path, formData).subscribe(
      (r)=>{console.log('got r', r)}
    )
  }

这篇关于使用HttpClient上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:12