如何使用 Angular 将图像作为二进制数据发送到我的 API?

问题描述 投票:0回答:1

我正在尝试根据卷曲请求提出角度请求,这个:

 curl -k -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/octet-stream" --data-binary '@/home/linux-user/Desktop/folder/cool-folder/src/assets/img/default-image.png' -X POST https://$ENDPOINT:6060/v1/user/photo\?id\=3591\&image\=996ab426-eb57-4f79-94f4-cfea9aef2cd9 |  gunzip | jq

*仅供参考:请求成功,但图像到达时已损坏,而且我也通过 api 将图像发送到 AWS

图像服务:

  private postHeaders(token: string): HttpHeaders {
      return new HttpHeaders({
        'Content-Type': 'application/octet-stream',
        Authorization: `Bearer ${token}`
      });
    }

uploadImage(file: File, token: string): Observable<any> {
      const headers = this.postHeaders(token);
  
      const formData = new FormData();
      formData.append('file', file);
  
      return this.http.post(this.endpoint, formData, { headers, responseType: 'text' })
        .pipe(
          map((response: any) => JSON.parse(response)),
          catchError((error: any) => throwError(error))
        );
    }

组件

onFileChange(event: any) {
    const file = event.target.files[0];
    console.log(file)
    if (file) {
      this.imageService.uploadImage(file, this.token)
        .subscribe((response) => {
          console.log(response); // Handle the response data here using 'jq' or other methods.
        }, (error) => {
          console.error(error);
        });
    }
  }


console.log(file)

上面组件的另一个示例

tried binary

 onFileChange(event: any) {
    const file = event.target.files[0];
    console.log(file)
    if (file) {
      this.readFileContent(file);
    }
  }

  readFileContent(file: File) {
    const reader = new FileReader();

    reader.onload = (e: any) => {
      const binaryData = e.target.result; // This contains the binary data of the file

      this.imageService.uploadImage(new Blob([binaryData]), this.token)
        .subscribe((response) => {
          console.log(response); // Handle the response data here
        }, (error) => {
          console.error(error);
        });
    };

    reader.readAsArrayBuffer(file);
  }

HTML

<input type="file" (change)="onFileChange($event)">
angular amazon-web-services post httprequest
1个回答
0
投票

显然,简单地传递文件应该可以工作,根据: http://www.sibenye.com/2017/02/17/handling-image-upload-in-a-multitiered-web-application-part- 1/

FormData
必须更好地用于发送
multipart/form-data

onFileChange(event: any) {
    const file = event.target.files[0];
    console.log(file)
    if (file) {
      this.readFileContent(file);
    }
    
    // part to send data
    let url = '/url';
    let headers = new Headers();
    headers.set('Content-Type', 'application/octet-stream');
    headers.set('Upload-Content-Type', file.type)
    // add authorization etc too
    let options = new RequestOptions({ headers: this.headers });
    this.http.post(url, file, options).subscribe()
  }
© www.soinside.com 2019 - 2024. All rights reserved.