我正在使用 Ionic 2,并创建了一个可以使用 Cordova 插件上传图像的应用程序。这在 iOS 和 Android 上完美运行。
我还想将上传功能添加到网络浏览器,但我无法访问 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
我认为我正在做一些根本错误的事情。任何建议表示赞赏。
最佳答案
这是一个有效的示例:
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);
}
关于javascript - HTML5 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43754265/