【问题标题】:How to send an image as a blob from Angular?如何从 Angular 将图像作为 blob 发送?
【发布时间】:2019-07-31 07:45:12
【问题描述】:

我正在使用文件输入标签来获取图像文件。现在,我想将它作为一个 blob 发送,我想将它作为字符串存储在数据库中。我将检索它并使用 get 调用将其渲染为图像。

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

【问题讨论】:

    标签: angular file-upload blob


    【解决方案1】:

    你可以像这样上传文件:

    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);
    
        }
      }
    
    }
    

    【讨论】:

      【解决方案2】:

      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】:

        来自这个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.");
              });
        }
        

        【讨论】:

          【解决方案4】:

          您可以使用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();
          }
          

          【讨论】:

          • 几乎没问题。但缺少 this._auth.uploadImg 的正文
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-07-23
          • 2020-07-20
          • 2020-10-01
          • 2020-07-27
          • 1970-01-01
          • 2020-11-01
          • 2018-02-15
          相关资源
          最近更新 更多