如何在 Angular 中使用 httpClient 发送文件?

How to sen file using httpClient in Angular?

我尝试使用 HttpClient:

发送文件
 public async uploadProfile(data: UploadProfile): Promise<any> {
    return await this.http.post(this.uploadProfileUrl, data).toPromise();
 }

在发送文件之前,我将其准备为二进制数组:

interface UploadProfile {
    file: any;
}


file = [123, 10, 32, 32, 34, 100, 105, 115, 97, 98, 108, 101, 83, 105, 122, 101, 76, 105, 109]

但是我得到错误:

TypeError: Cannot read property 'toLowerCase' of undefined
    at HttpXsrfInterceptor.intercept (http.js:2177)

这可能是由于您的请求期间未定义 url。尝试执行以下操作作为测试:

变化:

 public async uploadProfile(data: UploadProfile): Promise<any> {
    return await this.http.post(this.uploadProfileUrl, data).toPromise();
 }

收件人:

 public async uploadProfile(data: UploadProfile): Promise<any> {
    return await this.http.post('http://yourUrl/resource', data).toPromise();
 }

如果这行得通并且您不再看到错误,请在调用时尝试找出 uploadProfileUrl 未定义的原因。