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

时间:2019-03-09 12:33:32

标签: angular file-upload blob

我正在使用文件输入标签来获取图像文件。现在,我想将其作为Blob发送,并以String的形式存储在数据库中。我将检索它并通过get调用将其渲染为图像。

但是如何将图像发布为斑点?

4 个答案:

答案 0 :(得分:2)

您可以像这样上传文件:

TS

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Component, OnInit } from '@angular/core';



@Injectable({
    providedIn: "root"
})
export class UploadService {

    constructor(private httpClient: HttpClient) {
    }

  
    public uploadFile<T>(file: File): Observable<T> {
        let formData = new FormData();
        formData.append('file', file, file.name);

        var request = this.httpClient
            .post<T>(
                "url/to/backend/upload",
                formData
            );
        return request;

    }

}


@Component({
  selector: 'app-carga',
  templateUrl: './carga.component.html',
  template:
  `
           <input class="form-control" #fileInput type="file" [multiple]="false"/>
     <button type="button" class="btn btn-outline-success"
    (click)="uploadFile(fileInput)">Cargar</button>
  `

})
export class CargaComponent implements OnInit {

  constructor(public uploader: UploadService) {
  }

  ngOnInit(): void {
  }
  public uploadResult?: any;

  async uploadFile(fileInput: any) {
    let files: File[] = fileInput.files;
    if (files.length < 1) {
      return;
    }

    let file = files[0];
    try {

      this.uploader.uploadFile(file)
    .subscribe(result => {
      console.log(result);
      fileInput.value = null;
    },
      error => {
        console.error(error);
      })

    } catch (error) {

      console.warn("File upload failed.");
      console.error(error);

    }
  }

}

答案 1 :(得分: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.");
      });
}

答案 2 :(得分: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);
}

答案 3 :(得分: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();
}