手頭上的這個項目主要是在微信內運行的一個網站,需要用戶上傳手機內的照片,而現在手機照片尺寸越來越大,直接上傳的話的確上傳進度慢影響用戶體驗而且也會給服務器增加壓力,所以利用H5的新特性壓縮後上傳不失爲一良策。
最後選用的是localResizeImg進行壓縮上傳,簡單易上手,核心代碼部分如下。
前臺部分
<input id="upload" type="file" name="upload" multiple accept="image/*;capture=camcorder">
js部分:
var photoIdx=0;
document.querySelector('#upload').addEventListener('change', function () {
var filesCount = this.files.length;
if(filesCount>18) return zalert('最多隻能上傳18張照片');
var uploadedCount = $('.img-preview-box img').size();
if(uploadedCount>17) return zalert('最多隻能上傳18張照片');
var imageType = /^image\//;
var container = $('.img-preview-box');
if(filesCount>0 && imageType.test(this.files[0].type)) container.css({'min-height':'110px','overflow':'visible'})
for(var i=0,file;i<filesCount,file=this.files[i];i++){
if (!imageType.test(file.type)) { return zalert("上傳的圖片格式不正確,請重新選擇")}
photoIdx++;
lrz(file).then(function (rst) {
container.append('<div class="uploadimg-box"><img src="'+ rst.base64 +'"/><div class="del-uploadimg-box" title="移除該照片" data-id="'+ photoIdx +'"></div></div>');
return rst;
}).then(function (rst) {
rst.formData.append('fileLen', rst.fileLen);
$.ajax({
url: '/h5/photo/upload',
data: rst.formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
var photos=$('#uploadedPhotos').val();
$('#uploadedPhotos').val(photos+','+ data.url);
}
});
}).catch(function (err) {}).always(function () {});
}
});
PHP後臺部分:
public function upload()
{
$config = [
'size' => 2097152,
'ext' => 'jpg,gif,png,bmp'
];
$file = $this->request->file('file');
$upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads/photos');
$save_path = '/public/uploads/photos/';
$info = $file->validate($config)->move($upload_path);
if ($info) {
$result = [
'error' => 0,
'url' => str_replace('\\', '/', $save_path . $info->getSaveName())
];
} else {
$result = [
'error' => 1,
'msg' => $file->getError()
];
}
return json($result);
}