js实现获取手机相册并上传
在写易沃克项目时,一直苦于无路去实现将图片上传至服务器 。这是我的解决方案
当初有很多人说使用form方法将文件封装来上传,可是因为要照顾到从相机中选择图片,所以一直没有去做。 后来看到了Uploader的方法来传文件,感觉自己找到了 。他是使用plus.uploader来完成的
创建网络上传任务
function createUploader() {
task = plus.uploader.createUpload(url, {
method: 'POST'
}, function(data, status) {
if(status == 200) {
plus.nativeUI.closeWaiting();
var page = plus.webview.getWebviewById('view/dynamics/dynamics.html');
mui.fire(page, 'refresh', {});
mui.openWindow({
id: 'index.html'
});
} else {
mui.alert(status);
}
});
}相机拍照并获取到图片
//从相机中选取图片
function clickCamera() {
var c = plus.camera.getCamera();
c.captureImage(function(e) {
plus.io.resolveLocalFileSystemURL(e, function(entry) {
var path = entry.toLocalURL();
var name = name = path.substr(e.lastIndexOf('/') + 1);
//压缩图片到内存
plus.zip.compressImage({
src: path,
dst: '_doc/' + path,
quality: 20,
overwrite: true
}, function(zip) {
camera_photos.push({
path: zip.target
});
photos.push({
path: zip.target
});
showPhotos();
}, function(error) {
console.log("压缩error");
});
}, function(e) {
mui.toast("读取拍照文件错误" + e.message);
});
})
};获取手机相册,并为多选
var max = 9; //照片的最大数目
var galleryPhotoNum;
var galleryFiles;
function clickGallery() {
//确定还可以从相册中选择照片的最大数目
galleryPhotoNum = max - camera_photos.length;
plus.gallery.pick(function(path) {
galleryFiles = path.files;
plus.nativeUI.showWaiting();
compressImg(galleryFiles, 0);
}, function(e) {
console.log("获取照片失败");
}, {
filter: "image",
multiple: true,
maximum: galleryPhotoNum,
system: false,
onmaxed: function() {
mui.toast('最多选' + galleryPhotoNum + '个');
},
popover: true,
selected: galleryFiles
});
}同时获取到多张图片那么图片的压缩便成了问题 ,我使用的是plus.zip.compressImage()来做,但是如果通过一个for循环来对图片进行压缩是无法完成的 。
因为for循环速度很快,而plus.zip.compressImg是异步执行的,而且手机执行的压缩方法是有限制的,3个,超过就直接不执行了。所以我们要保证当一张压缩成功之后,再执行下一张, 通过递归来保证
//递归压缩图片
function compressImg(files, file_index) {
var file_length = files.length;
var path = files[file_index];
plus.zip.compressImage({
src: path,
dst: '_doc/' + path,
quality: 20,
overwrite: true
}, function(zip) {
var next_file_index = file_index + 1;
if(file_index == 0) {
gallery_photos = [];
}
gallery_photos.push({
path: zip.target
});
addPhoto(zip.target, file_index);
if(next_file_index < file_length) {
compressImg(files, next_file_index);
} else {
showPhotos();
}
})
}有点不对,好像有点跑题
继续前面提的文件上传, 上面我们新建了文件上传对象task
如果我们想传值,task.addData(‘name’,value);
如果想传文件,task.addFile(path,{ key:file.name });
当所需要上传的值,都加入之后,便可以使用task.start();
来开始所有任务了
task.addData('objectID', this_phoneNum);
task.addData('describe', content);
task.addData('position', "");
task.addData('num', '' + len);
for(var i = 0; i < len; i++) {
var j = i + 1;
var temp = 'phone' + j;
task.addFile(photos[i].path, {
key: temp
});
}
task.start();
来源:https://blog.csdn.net/qq_32635069/article/details/72869100
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!