如何从Angular发送图像作为blob?

问题描述 投票:-1回答:3

我正在使用文件输入标记来获取图像文件。现在,我想将它作为blob发送,我想将其作为String存储在数据库中。我将检索它并将其渲染为带有get调用的图像。

但是如何将图像作为blob发布?

angular file-upload blob
3个回答
0
投票

从这reference

你的'getBlob'服务:

getBlobThumbnail(): Observable<Blob> {  
  const headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  });
  return this.httpClient.post<Blob>(this.thumbnailFetchUrl,
    {
      "url": "http://acs/container/Logo.png"
    }, {headers: headers, responseType: 'blob' as 'json' });
}

你的组件:

imageBlobUrl: string;
getThumbnail() : void {
  this.ablobService.getBlobThumbnail()
    .subscribe(
      (val) => { 
        this.createImageFromBlob(val);
      },
      response => {
        console.log("POST in error", response);
      },
      () => {
        console.log("POST observable is now completed.");
      });
}

0
投票

I agree with comment above . This is an example for you

或者你可以使用dataForm如下:

 uploadPicture(formData: FormData, code: string) {
    // /** In Angular 5, including the header Content-Type can invalidate your request */
    const headers = new HttpHeaders();
    headers.append('Content-Type', null);
    headers.append('Accept', 'application/json');
    const options =  {
        headers: headers
    };

    const url = this.xxxServiceURL + '/custom/xxx/uploadPicture/' + code;
    return this.httpClient.post(url, formData, options);
}

0
投票

您可以使用FormData() HTML发送它

<input name="image" type="file" (change)="file($event)" required>

TS

file(event) {
  let elem = event.target;
  if(elem.files.length > 0) {
    let formData = new FormData();
    formData.append('file', elem.files[0], elem.files[0].name)
    this._auth.uploadImg(formData) //send it to service so you can make http call and send it as a post method to the backend
      .subscribe((data) => {
        console.log(data) //Image name
      },
        (error) => {
          console.log('error: ', error)
      })
  }
}

PHP

$imageFolder = "images/";

if(isset($_FILES)) {        
    if(preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $_FILES['file']['name'])){ //checking file name in english
        echo json_encode('Invalid name');
        exit();
    }

    if(!in_array(strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))){ // checking file extension
        echo json_encode('Invalid extension');
        exit();
    }

    $name = explode('.', $_FILES['file']['name']);
    $ext = end($name);
    $name = reset($name).md5($date).'.'.$ext;
    $filetowrite = $imageFolder . $name;
    move_uploaded_file($_FILES['file']['tmp_name'], $filetowrite); //move the image to the directory defined in $imageFolder variable above

    echo json_encode($name); //return current image name to angular
    exit();
} else {
    echo json_encode('No such file');
    exit();
}
© www.soinside.com 2019 - 2024. All rights reserved.