【发布时间】:2016-05-23 13:27:38
【问题描述】:
我正在使用图像选择器 (cordova-imagePicker) 插件从图库中获取图像并将它们上传到服务器。
我正在使用带有 Android 平台 5.1.1 和以下插件的 Cordova 6.1.1:
cordova-plugin-camera 2.2.0 "Camera"
cordova-plugin-compat 1.0.0 "Compat"
cordova-plugin-device 1.0.1 "Device"
cordova-plugin-file 4.2.0 "File"
cordova-plugin-imagepicker 1.1.0 "ImagePicker"
cordova-plugin-inappbrowser 1.4.0 "InAppBrowser"
cordova-plugin-media 2.3.0 "Media"
作为插件的回调,我正在使用以下代码将获得的路径转换为文件。请注意,我使用 resolveFile 是因为此代码也在桌面上运行,在这种情况下,该条目已经是一个 File 对象。
var resolveFile = function(entry) {
if (typeof(entry) === "string") {
var deferred = $q.defer();
// first convert to local file system URL
window.resolveLocalFileSystemURL(entry, function(fileEntry) {
// now read/convert the file to file object.
fileEntry.file(function(file) {
console.log("File converted to file entry");
deferred.resolve(file);
}, function(err) {
console.log("Failed to convert to file entry", err);
deferred.reject(err);
});
}, function(err) {
console.log("Failed to resolve to file URL", err);
deferred.reject(err);
});
return deferred.promise;
} else {
return $q.when(entry);
}
};
这又用于读取图像并将其传递给将其上传到服务器的函数($files 是我从插件或桌面/浏览器的输入中获得的):
var upload = function () {
if (!$files[currentFile]) {
onAllFinished();
return;
}
file = $files[currentFile];
beforeLoad(file);
fileReader = new FileReader();
fileReader.onload = onload;
fileReader.onprogress = progress;
resolveFile(file).then(function(actualFile) {
fileReader.readAsDataURL(actualFile);
});
currentFile++;
};
在上面,onload 剪切图像数据(在字符串中的“base64”之后)并将其发送到需要 base64 字符串的上传代码,并使用简单的 AJAX 调用将数据上传到服务器:
var uploadPhoto = function(url, photo, callback, error)
$http.post(url, {
photo: photo,
})
.success(callback)
.error(function (data, status, headers, config) {
if (error)
error(data, status, headers, config);
});
最后一个函数也适用于相机插件 camera plugin 使用 DATA_URI 目标(我知道,不推荐),它还返回一个 base64 字符串(所以我可以重用代码)。
在我看来,文件阅读器输出有问题(我猜)。 (我认为)暗示的是,小图像(10s kb)可以很好地加载,并且已经从相机插件中准备好了base64字符串,但是通过文件读取器(在Android上,在桌面上它很好)更大的图像(几MB) ) 上传已损坏(见下文)。
有人遇到过这样的问题吗?任何人都可以提出修复建议(除了更改代码以使用 FileTransfer 插件)吗?
原图:
上传的(损坏的)图片。请注意,其中一些可以正常阅读/上传:
【问题讨论】:
标签: javascript android image cordova filereader