1
我正在使用Ionic 2,並創建了一個可以使用Cordova插件上傳圖片的應用程序。這適用於iOS和Android。HTML5上傳文件
我也想將上傳功能添加到網頁瀏覽器,但是我沒有權限訪問Cordova插件。因此,我認爲這樣做的最好方法是使用HTML5:
<input *ngIf="!isCordova" id="file" type="file" accept="image/*">
這就產生預期的輸入元素:
問題
我現在該如何處理選擇的圖像文件?
在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
我想我正在做一些根本性的錯誤。任何意見讚賞。