🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 文件上传 零云默认使用了百度的webuploader插件来实现文件上传,除了使用这个,当然你也可以自己使用自己熟悉的插件,插件请放到/Application/当前模块/View/Public/libs目录下然后用__LIBS__/test.min.js调用 ## 说明 如果在一个页面中有2个以上上传按钮,请注意修改按钮的唯一ID不要冲突。 ![](/Uploads/manual/image/2018-10-27/5bd439ade6087.png) ## 示例 ```html <extend name="$_home_public_layout"/> <block name="style"> <style type="text/css"> #preview-pane .preview-container { width: 200px; height: 200px; overflow: hidden; } </style> </block> <block name="main"> <div class="container"> <div class="row"> <div class="col-xs-12 col-md-9"> <div class="panel panel-default"> <div class="panel-body"> <div class="m-t-md"> <h4>上传自定义头像</h4> <form method="post" action="{:U('User/Center/avatar')}" class="avatar-form"> <div class="form-group"> <div id="crop-pane" class="row"> <div id="upload_list" class="uploader-list col-xs-12 img-box"> <div id="upload_preview" class="col-md-4 file-item thumbnail m-b-xs"> <img class="crop" src=""> </div> </div> </div> </div> <div class="form-group"> <input type="hidden" name="avatar" id="upload-avatar-src"> <a id="upload-avatar-button" class="btn btn-primary m-b">上传头像按钮</a> <button type="submit" class="submit btn btn-success m-b ajax-posts" target-form="avatar-form">保存头像</button> </div> </form> </div> </div> </div> </div> </div> </div> </block> <block name="script"> <script type="text/javascript" src="__PUBLIC__/libs/webuploader/webuploader.min.js"></script> <script type="text/javascript"> $(function(){ // 上传头像 var uploader = WebUploader.create({ withCredentials: true, auto: true, duplicate: true, server: '{:U(MODULE_MARK."/Upload/upload", array("temp" => "true"), true, true)}', pick: '#upload-avatar-button', resize: false, fileNumLimit: 20, fileSingleSizeLimit: "<php> echo C('UPLOAD_FILE_SIZE') ? : 2; </php>*1024*1024", accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png' } }); // 文件上传过程中创建进度条实时显示。 uploader.on( 'uploadProgress', function( file, percentage ) { $( '#upload_preview').removeClass('hidden'); var $li = $('#upload_preview'), $percent = $li.find('.progress .progress-bar'); // 避免重复创建 if ( !$percent.length ) { $percent = $('<div class="progress"><div class="progress-bar"></div></div>').appendTo( $li ).find('.progress-bar'); } $percent.css( 'width', percentage * 100 + '%' ); }); // 完成上传完了,成功或者失败,先删除进度条。 uploader.on( 'uploadComplete', function( file ) { $( '#upload_preview' ).find('.progress').remove(); }); // 文件上传成功,给item添加成功class, 用样式标记上传成功。 uploader.on( 'uploadSuccess', function( file , response) { $( '#upload_preview' ).addClass('upload-state-done'); if(eval('response').status == 0){ $.alertMessager(response.info); } else { $( '#upload-avatar-src' ).attr('value', response.id); // 上传成功后会得到图片ID把这个ID设置到表单里,下一步提交。 $( '#upload_preview img').attr('src', response.url); // 预览图片 } }); }); </script> </block> ```