2017-05-03 3 views
1

私はIonic 2を使用しており、Cordovaプラグインを使用して画像をアップロードできるアプリを作成しました。これはiOSとAndroidで完全に動作します。HTML5アップロードファイル

アップロード機能をウェブブラウザに追加したいと思いますが、私はCordovaプラグインにアクセスできません。だから私はそれを行うための最善の方法は、HTML5を使用していると思わ:

<input *ngIf="!isCordova" id="file" type="file" accept="image/*"> 

予想通りこれは、入力要素を作成します。私は今、処理するにはどうすればよい

enter image description here

が質問

選択したイメージファイル?

Ionicでは、私は次のことを行い、選択した画像のjavascriptでこれに相当するものを望みます。

// using the Camera plugin 
Camera.getPicture(options).then((imageURI) => { 
this.toBase64(imageURI).then((base64Img) => { 
         this.base64Image = base64Img; 
         // process further 
         // .... 
}); 

toBase64(url: string): Promise<string> { 
    return new Promise<string>(function (resolve) { 
     var xhr = new XMLHttpRequest(); 
     xhr.responseType = 'blob'; 
     xhr.onload = function() { 
      var reader = new FileReader(); 
      reader.onloadend = function() { 
       resolve(reader.result); 
      } 
      reader.readAsDataURL(xhr.response); 
     }; 
     xhr.open('GET', url); 
     xhr.send(); 
    }); 
} 

resize(base64Img: string, width: number, height: number): string { 
    var img = new Image(); 
    img.src = base64Img; 
    var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'); 
    canvas.width = width; 
    canvas.height = height; 
    ctx.drawImage(img, 0, 0, width, height); 
    return canvas.toDataURL("image/jpeg"); 
} 

あなたが見ることができるように、私はimageURIのハンドルを取得する必要があります。私はそうする方法がわかりません。私は、次のことを試してください。

ionViewDidEnter() { 
    this.myInput = document.getElementById('file'); 
    let that = this; 
    this.myInput.addEventListener('change', function() { 
     let file: HTMLInputElement = this.files[0]; 
     console.log(file); 
    }, false); 
} 

これは、選択したファイルのハンドルを取得し、私はimageURIを得るように見えることはできません。

File {name: "SA 02 041.jpg", lastModified: 1227564968000, lastModifiedDate: Tue Nov 25 2008 00:16:08 GMT+0200 (SAST), webkitRelativePath: "", size: 902809…} 
lastModified 
: 
1227564968000 
lastModifiedDate 
: 
Tue Nov 25 2008 00:16:08 GMT+0200 (SAST) 
name 
: 
"SA 02 041.jpg" 
size 
: 
902809 
type 
: 
"image/jpeg" 
webkitRelativePath 
: 
"" 
__proto__ 
: 
File 

私は基本的に間違ったことをしています。どんな助言も高く評価されます。ここで

答えて

1

は作品例です。

ionViewDidEnter() { 
    this.myInput = document.getElementById('file'); 
    let that = this; 
    this.myInput.addEventListener('change', function (evt) { 
     var files = evt.target.files; 
     for (var i = 0, f; f = files[i]; i++) { 
      if (!f.type.match('image.*')) { 
       continue; 
      } 
      var reader = new FileReader(); 
      // Closure to capture the file information. 
      reader.onload = (function (theFile) { 
       return function (e) { 
        console.log(theFile); 
        console.log(e.target.result); 
       }; 
      })(f); 

      // Read in the image file as a data URL. 
      reader.readAsDataURL(f); 
     } 
    }, false); 
}