手頭上的這個項目主要是在微信內運行的一個網站,須要用戶上傳手機內的照片,而如今手機照片尺寸愈來愈大,直接上傳的話的確上傳進度慢影響用戶體驗並且也會給服務器增長壓力,因此利用H5的新特性壓縮後上傳不失爲一良策。css
<input id="upload" type="file" name="upload" multiple accept="image/*;capture=camcorder">
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 () {});
}
});
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);
}