移动端H5上传图片并压缩上传

手头上的这个项目主要是在微信内运行的一个网站,须要用户上传手机内的照片,而如今手机照片尺寸愈来愈大,直接上传的话的确上传进度慢影响用户体验并且也会给服务器增长压力,因此利用H5的新特性压缩后上传不失为一良策。css

最后选用的是localResizeImg进行压缩上传,简单易上手,核心代码部分以下。ajax

前台部分json

<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);
    }
相关文章
相关标签/搜索