簡體   English   中英

ionic 4 (android) 從圖庫 (FILE_URI) 獲取圖像 (OBJECT FILE) 並通過 API 上傳

[英]ionic 4 (android) get image (OBJECT FILE) from gallery (FILE_URI) and upload via API

我正在嘗試使用Ionic v4 angular 和cordova實現一個簡單的應用程序 只需選擇一張照片並將其上傳到解析服務器 (back4app.com) 即可 但我做不到。

這是我的代碼:

主頁.ts

import { ParseService } from '../service/parse.service';

import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
import { File } from '@ionic-native/file/ngx';
import { WebView } from '@ionic-native/ionic-webview/ngx';
  selectPhoto() {
    const options: CameraOptions = {
      quality: 100,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      destinationType: this.camera.DestinationType.FILE_URI,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      correctOrientation: true 
    }
    this.camera.getPicture(options).then((imageData) => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64 (DATA_URL):
      // let base64Image = 'data:image/jpeg;base64,' + imageData;
      // console.log(imageData);

      this.fileToUpload = imageData;

      this.phototoshow = this.webview.convertFileSrc(imageData);

    }, (err) => {
      // Handle error
    });
  }
 onSubmit() {

    this.presentLoading();

    // return this.apiService.upload(this.phototoshow).subscribe((data: any) => {
    return this.apiService.upload(this.fileToUpload).subscribe((data: any) => {
          console.log(data);
    }
}

服務.ts

upload(img1): Observable<any> {
    // console.log(data);
    return this.http.post(this.apiURL + '/files/img.jpg', img1,{
      headers: {
        'X-Parse-Application-Id': this.APP_ID,
        'X-Parse-REST-API-Key': this.REST_API_KEY,
        'Content-Type':'image/jpeg'
      }
    })
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }

我能夠以表單中的“輸入類型=文件”上傳圖像......但是使用cordova插件相機從圖庫中選擇圖像......它只返回FILE_URI但我需要OBJECT FILE通過api rest上傳.

我在網上閱讀了足夠多的信息,但這些舊信息對我沒有幫助。 我希望有人能幫我解決這個問題。 謝謝

我設法解決了這個問題:

  startUpload() {
      this.file.resolveLocalFilesystemUrl(this.fileToUpload)
      // this.file.resolveLocalFilesystemUrl(imgEntry.filePath)
          .then(entry => {
              (entry as FileEntry).file(file => this.readFile(file))
          })
          .catch(err => {
              alert('Error while reading file.');
          });
  }

  readFile(file: any) {
      const reader = new FileReader();
      reader.onload = () => {
          const imgBlob = new Blob([reader.result], {
              type: file.type
          });
          this.onSubmit(imgBlob);
      };
      reader.readAsArrayBuffer(file);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM