Home >Web Front-end >Bootstrap Tutorial >Usage of Bootstrap File Input
This article introduces how to use Bootstrap File Input (the best file upload component) to display and upload images, and how to upload files on the server side save.
bootstrap basic tutorial》
2. Introducing the plug-in styles and scripts<link type="text/css" rel="stylesheet" href="${ctx}/components/fileinput/css/fileinput.css" /> <script type="text/javascript" src="${ctx}/components/fileinput/js/fileinput.js"></script> <script type="text/javascript" src="${ctx}/components/fileinput/js/fileinput_locale_zh.js"></script>
<input type="file" name="image" class="projectfile" value="${deal.image}"/>
projectfileoptions : { showUpload : false, showRemove : false, language : 'zh', allowedPreviewTypes : [ 'image' ], allowedFileExtensions : [ 'jpg', 'png', 'gif' ], maxFileSize : 2000, }, // 文件上传框 $('input[class=projectfile]').each(function() { var imageurl = $(this).attr("value"); if (imageurl) { var op = $.extend({ initialPreview : [ // 预览图片的设置 "<img src='" + imageurl + "' class='file-preview-image' alt="Usage of Bootstrap File Input" >", ] }, projectfileoptions); $(this).fileinput(op); } else { $(this).fileinput(projectfileoptions); } });
allowedFileTypes and allowedFileExtensions. I don’t know why it doesn’t work?
<form class="form-horizontal required-validate" action="${ctx}/save?callbackType=confirmTimeoutForward" enctype="multipart/form-data" method="post" οnsubmit="return iframeCallback(this, pageAjaxDone)"> <div class="form-group"> <label for="" class="col-md-1 control-label">项目封面</label> <div class="col-md-10 tl th"> <input type="file" name="image" class="projectfile" value="${deal.image}" /> <p class="help-block">支持jpg、jpeg、png、gif格式,大小不超过2.0M</p> </div> </div> <div class="form-group text-center "> <div class="col-md-10 col-md-offset-1"> <button type="submit" class="btn btn-primary btn-lg">保存</button> </div> </div> </form>
function pageAjaxDone(json) { YUNM.debug(json); YUNM.ajaxDone(json); if (json[YUNM.keys.statusCode] == YUNM.statusCode.ok) { var msg = json[YUNM.keys.message]; // 弹出消息提示 YUNM.debug(msg); if (YUNM.callbackType.confirmTimeoutForward == json.callbackType) { $.showSuccessTimeout(msg, function() { window.location = json.forwardUrl; }); } } }
Its main function is to process the error message passed by the server through the ajaxDone method. If the server operation is successful, a prompt message will be displayed and then jump to the corresponding url.
6. Save images on the server side
$(this).fileinput()you wrote yourself. In fileinput.js, the allowedFileTypes and allowedFileExtensions values are not set.
There are two ways to change it:
1. Comment out the last few lines of calls in fileinput.js.
2. Use the "data-" method to do everything without writing $(this).fileinput().
I am very grateful to ihchenchen for his kind reminder. Although the explanation he provided did not solve my doubts, I really like such interactive technical exchanges. I wrote a lot of blogs before, and it rarely happened. Such a well-intentioned and effective answer. This reminds me of Chinese programmers and foreign programmers. The stories inside are shocking and a little bit embarrassing. So how to achieve "
Ask questions, get answers, no distractions." becomes particularly precious, and "ihchenchen" is full of this spirit! 6. Solve the doubts about allowedFileTypes and allowedFileExtensions
①、allowedFileTypes
allowedFileTypesarray the list of allowed file types for upload. This by default is set to null which means the plugin supports all file types for upload. If an invalid file type is found, then a validation error message as set in msgInvalidFileType will be raised. The following types as set in fileTypeSettings are available for setup.['image', 'html', 'text', 'video', 'audio', 'flash', 'object']
Let's start with "allowedFileTypes". This attribute tells us the file selection type. Then we can easily think of this picture:
也就是说,我们希望此时的“所有文件”处不是“所有文件”,而是“image”之类的。显然这样的逻辑并没有错,但却不适合bootstrap fileinput!
那么,这个时候我就很容易认为“allowedFileTypes” 没有起到作用!
但请看下图:
吼吼,原来是在你选择了文件后发生的类型检查!
$(this).fileinput({ showUpload : false, showRemove : false, language : 'zh', allowedPreviewTypes: ['image'], allowedFileTypes: ['image'], allowedFileExtensions: ['jpg', 'png'], maxFileSize : 2000, });
通过fileinput方法我们加载一个bootstrap fileinput组件,那么其内部是如何实现allowedFileTypes的呢?
通过在fileinput.js文件中搜索“allowedFileTypes”关键字,我们得到如下代码:
var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i], caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '', previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk, fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '), fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
然后我们继续看到如下的代码:
if (!isEmpty(fileTypes) && isArray(fileTypes)) { for (j = 0; j < fileTypes.length; j += 1) { typ = fileTypes[j]; checkFile = settings[typ]; chk = (checkFile !== undefined && checkFile(file.type, caption)); fileCount += isEmpty(chk) ? 0 : chk.length; } if (fileCount === 0) { msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes); self.isError = throwError(msg, file, previewId, i); return; } }
我们可以发现,文件类型的检查是发生在checkFile方法上,那么checkFile方法到底做了些什么呢?
defaultFileTypeSettings = { image: function (vType, vName) { return (vType !== undefined) ? vType.match('image.*') : vName.match(/\.(png|jpe?g)$/i); }, ...
以上就是checkFile的内容。
也就是说当我们指定allowedFileTypes: ['image'],
时,就会进行image的类型检查。
显然我们选择的txt文件不属于image类型,那么就会匹配不上,出现以上界面。
同时,该方法告诉我们,当不指定allowedFileTypes: ['image'],
,只指定allowedFileExtensions: ['jpg', 'png'],
就会执行vName.match(/\.(png|jpe?g)$/i)
,也就是文件后缀类型的检查,这点很关键啊,为我们接下来介绍“allowedFileExtensions”奠定基础。
上节我们讨论完“allowedFileTypes”,捎带说了“allowedFileExtensions”,那么如何让后缀进行check呢?
$(this).fileinput({ showUpload : false, showRemove : false, language : 'zh', allowedPreviewTypes: ['image'], allowedFileExtensions: ['jpg', 'png'], maxFileSize : 2000, });
fileinput组件此时指定的属性如上,没有了“allowedFileTypes”,并且指定允许的后缀类型为“[‘jpg’, ‘png’]”,也就是说,假如我们选择了gif的图片就会出现错误提示。
错误预期的发生了,那么请特别注意:
image: function (vType, vName) { return (vType !== undefined) ? vType.match('image.*') : vName.match(/\.(png|jpe?g)$/i); },
fileinput.js文件中原始的代码如下:
image: function (vType, vName) { return (vType !== undefined) ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i); },
image类型的后缀当然默认包含了gif,我只是为了举例说明,代码做了调整,请注意!
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Usage of Bootstrap File Input. For more information, please follow other related articles on the PHP Chinese website!