在前端开发过程当中,咱们常常要上传文件,这是咱们就要用
<input type="file" name="file">
这是原生的写法,看起来不是很美观。下面咱们聊一种比较优雅的实现方法。javascript
首先,咱们隐藏的
input
框,并将input
框的click事件绑定到它上面的button
元素上(经过onclick="$(this).next().click()"
实现),这样咱们就能够按照咱们本身的喜爱来设置button
的样式,同时也达到了上传文件的功能。css
<button type="button" onclick="$(this).next().click()"> <i class="fa fa-upload mr-sm" aria-hidden="true"></i><span>导入</span> </button> <input type="file" name="file" style="display:none" class="btn-upload">
jQuery File Upload
是一个Jquery
文件上传组件,支持多文件上传、取消、删除,上传前缩略图预览、列表显示图片大小,支持上传进度条显示;支持各类动态语言开发的服务器端。
咱们这里主要说说文件上传和文件格式、 大小的要求前端
fileupload
插件是必须的,fileupload-process
负责处理上传过程当中各个事件的管理,fileupload-validate
则是对验证的支持java
<script src="//cdn.bootcss.com/blueimp-file-upload/9.12.5/js/jquery.fileupload.js"></script> <script src="//cdn.bootcss.com/blueimp-file-upload/9.12.5/js/jquery.fileupload-process.js"></script> <script src="//cdn.bootcss.com/blueimp-file-upload/9.12.5/js/jquery.fileupload-validate.js"></script>
咱们能够对上传文件的大小和文件类型进行验证,并经过
messages
设置验证失败时的提示信息。jquery
$('input[name="file"]').fileupload({ url: '上传地址', Type: "POST", autoUpload: true, acceptFileTypes:/\.(doc|docx)$/i,// 文件格式 maxFileSize: 99 * 1024 * 1024, //文件大小 // 设置验证失败的提示信息 messages: { maxFileSize: 'File exceeds maximum allowed size of 99MB', acceptFileTypes: 'File type not allowed' }, processfail: function (e, data) { var currentFile = data.files[data.index]; if (data.files.error && currentFile.error) { // there was an error, do something about it console.log(currentFile.error); } }, done: function() { // 上传成功的回调函数,能够弹出“上传成功”之类的弹框 }, fail: function() { // 上传失败的回调函数,能够弹出“上传失败”之类的弹框 }, })
Jquery
有不少很好用的插件,逐个去学习不是很现实,只有在用到的时候,尽力去搞懂其使用方法。慢慢积累吧~~~服务器