file input插件功能如此强大,样式非常美观,并且支持上传文件预览,ajax同步或异步上传,拖曳文件上传等炫酷的功能,完全没有理由不去使用,但是国内很少能找到本插件完整的使用方法,于是本人去其官网翻译了一下英文说明文档放在这里供英文不好的同学勉强查阅。另外附上一段调用方发和servlet端的接收代码,未完待续。
英文原版地址:http://plugins.krajee.com/file-input
下文是翻译,有很多不通顺的地方其实是我也没读懂,大家请不要见怪,不知道怎么回事这篇博客突然又很多人看,以前翻译的估计我的英文老师会亲自来打我,于是今天得空又仔细翻译了一遍,由于长时间没做过js了大家有问题也不要问我了,我也没试过。。。
引言:
An enhanced HTML 5 file input for Bootstrap 3.x with file preview for various files, offers multiple selection, and more. The plugin allows you a simple way to setup an advanced file picker/upload control built to work specially with Bootstrap CSS3 styles. It enhances the file input functionality further, by offering support to preview a wide variety of files i.e. images, text, html, video, audio, flash, and objects. In addition, it includes AJAX based uploads, dragging & dropping files, viewing upload progress, and selectively previewing, adding, or deleting files.
fileinput是一个增强的基于Bootstrap3.x和HTML5的文件上传工具,具备多种格式文件的预览功能,并提供了诸如文件多选等诸多功能。本插件为你配置了一个先进而简单的文件选择/上传方式并且融合了了Bootstrap CSS3样式。它通过显示很多种文件的预览图,像图片,文本,html,视频,音频,flash和其他文件等,极大的丰富了文件上传的功能,另外,它包含了基于AJAX的上传,拖拽和撤销文件,显示上传进度和可以任意选择的预览,添加,删除文件。
View a complete demo.点击此处查看一个完整的demo
With release v4.0.0, the plugin now supports AJAX based uploads using HTML 5 FormData and XHR2 protocol, which is supported in most modern browsers. It also has inbuilt support for AJAX based file deletion from the server. This thereby allows powerful features to append, add, remove files on the fly. The plugin also has added DRAG & DROP support for ajax uploads. In the event, the browser does not support FormData or XHR2, the plugin degrades it to a normal form submission.
在4.0.0版本中,该插件已经支持了基于AJAX的上传(使用HTML5 表单和XHR2协议),这种方式已经被很多浏览器所支持。该插件也原生支持了基于AJAX的服务器文件删除功能。因此你可以通过它在客户端实现诸如追加,添加,移出等酷炫的操作。本插件也添加了拖曳添加和拖曳删除的功能。如果你的浏览器不支持表单或者XHR2,本插件会自动的降级成一个普通的提交表单。
功能
提示:本插件的最新版本:v4.3.2已经放出
File Input Features/选择文件功能
-
The plugin will convert a simple HTML file input to an advanced file picker control. Will help fallback to a normal HTML file input for browsers not supporting JQuery or Javascript.
该插件会把简单的HTML文件输入框转换成一个先进的文件选择器。但是对于不支持JQuery和JS的浏览器会自动的回滚到普通的HTML文件输入框 -
The file input consists of the following three sections with options and templates to control the display:
该插件包含了下列的三个部分,并且都可以通过修改JS中代码模板上的选项来控制显示效果-
file caption section: to display a brief information of the file(s) selected
文件标题部分:显示一个被选文件的简介 -
file action buttons section: to browse, remove, and upload files.
文件动作按钮部分:用于浏览,移除和上传文件 -
file preview section: to display the selected files on client for preview (supports preview of image, text, flash, and video file types). Other file types will be displayed as normal thumbnails.
文件预览部分:在客户端展示被选择文件的预览图(现已经支持图片,文本,flash,视频文件)其他的文件会使用默认缩略图。
-
-
The plugin automatically converts an input with
type = file
to an advanced file picker input if you set itsclass = file
. All options to the input can be passed as HTML5data
attributes.
如果你设置一个普通的input控件(type=file)的class=file,该插件会自动的把这个input框转换成为一个先进的文件选择器,这个input的所有属性会被转换成HTML5 的data属性 -
Ability to select and preview multiple files. Uses HTML 5 File reader API to read and preview files. Displays the progress of files being being loaded onto the preview zone, in case many files are chosen.
该插件可以通过HTML5 File reader AP来读取,选择,和预览许多种文件。如果选择了许多文件进行上传,可以在预览区域中显示文件的上传进度 -
Offers predefined templates and CSS classes which can be changed to style your file-input display as per your needs.
提供了事先写好的模板和CSS,能够让你定义自己需要的风格 -
Ability to configure the plugin to show an initial preview of images/files with initial caption (more useful for record update scenarios). Refer the
initialPreview
,initialPreviewConfig
, andinitialCaption
properties in the plugin options section for configuring this.
你可以通过修改配置在初始化预览图的时候显示一个图片或文件的首字母(对于记录上传情景很有用)想实现这个功能的话可以在插件的选项中配置以下三个属性initialPreview
,initialPreviewConfig
,initialCaption
-
Ability to zoom content as a detailed preview. See a slideshow of zoomed content in preview, maximize to borderless or fullscreen preview.
该插件能够将缩略预览图的内容放大成一个精细的预览图。而且在看放大幻灯片的预览图的时候能够最大化到无边预览或者全屏预览 -
Ability to sort/rearrange content in the initial preview via drag and drop.
能够通过拖入和拖出在初始预览中对内容进行分类或者重新排列 -
Ability to theme the widget entirely and control styling and layouts.
能够将整个控件主题化并且可以修改风格和布局 -
Supports multi language widgets on same page through locales/translations.
支持本地化和翻译,能够在同一页面显示多语言控件 -
Option to show/hide any or all of the following:
可以通过需求显示或者隐藏如下部分-
caption section 标题部分
-
preview section 预览部分
-
upload button 上传按钮
-
remove button 删除按钮
-
-
Customise the location of the target container elements to display the entire plugin, the caption container, the caption text, the preview container, preview image, and preview status.
可以自定义这个插件的容器的位置来显示着整个插件,包括标题的容器,标题的文本,预览的容器,预览的图片和预览的状态 -
For text file previews, autowrap the text to the thumbnail width, and show a wrap indicator link to display complete text on hover. You can customize the wrap indicator (which defaults to …).
本插件可以自动的适配缩略图的宽度来显示文本文件的缩略图,并且还会显示一个收起的标志,点击以后可以上层看见这个文本文件的全部内容。而且你还可以自定义这个标志的图标(默认是三个点...) -
Customise the messages for preview, progress, and files selected.
自定义了预览图,进度条和被选择文件的message -
Upload action defaults to form submit. Supports an upload route/server action parameter for custom ajax based upload.
默认的上传动作是提交表单,但是也支持基于ajax的上传操作 -
Triggers JQuery events for advanced development. Events currently available are
filereset
,fileclear
,filecleared
,fileloaded
, andfileerror
.
可以使用JQuery的事件回调来实现更先进的项目部署。目前可以使用的事件包括filereset
,fileclear
,filecleared
,fileloaded
,fileerror
. -
Disabled and readonly file input support.
文件上传Input支持readonly(只读)和Disabled(禁用)这两个属性 -
Dynamically auto size the file captions for long file names exceeding container width.
对于文件名太长超过了容器的宽度时,该插件会自动的收缩文件标题 -
Raise new
fileimageuploaded
event that fires after image is completely loaded on the preview container.
添加了在预览框中图片已经完全加载完毕后回调的事件——fileimageuploaded -
Autosize preview images when they exceed the size of the preview container.
当图片的大小超出了预览框时,会自动的收缩预览图的大小 -
Completely templatized and extensible to allow configuration of the file-input the way the developer wants.
通过完整的配置模板为开发人员提供了超高的可扩展性 -
Preview intelligence based on various file preview types. The inbuilt file support types are categorized as
image
,text
,html
,video
,audio
,flash
,object
, andother
.
内置文件支持类型已经分类好了,可以智能的显示不同文件的预览图。文件预览图的种类包括:image
,text
,html
,video
,audio
,flash
,object
, andother
-
allowedPreviewTypes
: You can now configure which all file types are allowed to be shown as a preview. This defaults to['image', 'html', 'text', 'video', 'audio', 'flash', 'object']
. Thus all file types are treated as an object to preview by default. For exampleTo preview onlyimage
andvideo
, you can set this to['image', 'video']
. To disable content preview for all file-types and show thepreviewIcon
instead as a thumbnail, set this to null, empty, orfalse
.
allowedPreviewTypes(允许的预览图类型):你可以通过这个字段配置你允许可以被展示成缩略图的文件类型,默认值是['image', 'html', 'text', 'video', 'audio', 'flash', 'object'] 。因此所有类型的文件默认都会被当成一个object来展示。如果你想只显示图片和视频的缩略图,你可以设置这个字段为['image', 'video'] 。如果你想进制所有文件类型的内容缩略图并且只显示previewIcon
而非小图,你可以设置这个字段的值为null,空,或者false。 -
allowedPreviewMimeTypes
: In addition toallowedPreviewTypes
, you can also control which all mime types can be displayed for preview. This defaults to null, meaning all mime types are supported. >NOTE: With release 2.5.0 you can now control which file types or extensions are allowed for upload by settingallowedFileTypes
andallowedFileExtensions
.
allowedPreviewMimeTypes(允许预览图的媒体类型):除了使用上面说的allowedPreviewTypes 这个字段,你还可以通过mime type来控制预览图是否显示。这个字段的默认值是null,意味着所有的媒体类型都会被支持。注意:在2.5.0版本中你可以通过设置allowedFileTypes
和allowedFileExtensions
字段来限制何种类型的文件或者扩展可以被上传 -
layoutTemplates
: Allows you to configure all layout template settings within one property. The layout objects that can be configured are:main1
,main2
,preview
,caption
, andmodal
.
layoutTemplates(布局模板):可以让你在一个属性中设置所有的布局模板。这个布局中的元素可以被配置成main1
,main2
,preview
,caption
, andmodal
. -
previewTemplates
: All preview templates for each preview type have been combined into one property, instead of separate templates for image, text etc. The keys are the formats as set inallowedPreviewTypes
and values are the templates used for previewing. There are default prebuilt templates for each preview file type (generic
,image
,text
,html
,video
,audio
,flash
,object
, andother
). Thegeneric
template is used only for displayinginitialPreview
content using direct markup.
previewTemplates (预览图模板):每种预览图类型的模板已经被融合进了一个属性,而不是为图片,文本等类型配置单独的模板。设置在allowedPreviewTypes
中的格式和模板中用来预览的值是关键。每种预览文件的类型(generic
,image
,text
,html
,video
,audio
,flash
,object
, andother
).都会有提前配置好的默认模板。generic
模板仅仅用来展示使用直接标记的initialPreview
内容
-
previewSettings
: Allows you to configure width and height for each preview image type. The plugin has default widths and heights predefined for each type i.eimage
,text
,html
,video
,audio
,flash
, andobject
.
previewSettings (预览设置):你可以配置任何一种预览图的宽高。该插件已经为不同种类的文件(image
,text
,html
,video
,audio
,flash
, andobject
)提前定义好了一套默认的宽高。 -
fileTypeSettings
: Allows you to configure and identify each preview file type using a callback. The plugin has default callbacks predefined to identify each type i.eimage
,text
,html
,video
,audio
,flash
, andobject
.
fileTypeSeetings(文件类型设定):你可以通过一个回调来配置并且识别每种预览的文件类型。该插件已经为每种文件类型提前定义好了一套默认的回调函数来区分文件的类型,如image
,text
,html
,video
,audio
,flash
, andobject
-
Replacing tags within templates has been enhanced. With this release it will automatically check for multiple occurrences of each tag to replace within a template string.
模板中可替换的标签已经被增强了。在这个版本中,插件会自动的检查每个标签的复现情况来使用模板中的字符串进行替换#这句话我也不明白什么意思,有大神的话可以告诉我 -
Manipulate events and add your own custom validation messages easily by returning output to abort uploads in any of the other events.
你可以操纵回调事件并且可以轻松的通过服务器返回的输出值来添加你自定义的校验信息并可以凭此中断任何其他事件中的上传进程。 -
Support for translations and locales.
支持翻译和本地化
Note 注意
Flash preview will require Shockwave flash to be installed and supported by the client browser. The flash preview currently works successfully with webkit browsers only. Video & Audio formats are however supported by all modern browsers that support the HTML5video
/audio
tags. Note that browsers have limited number of video/audio formats supported by the HTML5 video element (e.g. mp4, webm, ogg, mp3, wav). The size of video files are recommended to be small (to be controlled through maxFileSize
property) so that it does not affect the preview performance. You can copy a few files from the examples
directory of this plugin repo, to test a few examples of flash and video files
Flsh的预览需要安装Shockwave flash并且你的浏览器还要支持这个插件。目前flash的预览仅能在webkit内核的浏览器上成功运行。能在HTML5video
/audio
标签中播放的视频格式都已经支持预览。注意浏览器已经限制了HTML5支持的视频和音频格式(比如mp4,webm,ogg,mp3,wav).视频大小应该小一点(可以通过maxFileSize
这个属性进行限制)来保证预览效果的流畅性。你可以从该插件的代码库的examples
目录中拷贝一些文件来测试flash和视频的预览效果。
File Upload Features 文件上传功能
With release 4.0.0, the plugin now also includes inbuilt support for AJAX Uploads and selectively adding or deleting files. AJAX upload functionality are built upon HTML5 FormData and XMLHttpRequest Level 2 standards. Most modern browsers do support this standard, but the plugin will automatically degrade to normal form based submission for unsupported browsers.
在4.0.0版本中,该插件已经内置AJAX上传功能并可以自由的添加删除文件。AJAX上传功能必须再在浏览器支持HTML5表单和XMLHttpRequest Level 2的环境中使用。但是许多浏览器并不支持这些标准,好在该插件在这些浏览器上会自动的降级成一个普通的文件提交表单。
-
Add functionality for AJAX based UPLOAD using HTML5 FormData (most modern browsers support it). Will degrade to normal Form Based File submission if this is not supported.
添加了基于HTML5 表单的AJAX上传功能。如果你的浏览器不支持HTML5该插件会自动降级成一个普通表单。 -
To use AJAX Upload, one must set the
uploadUrl
property.
如果要使用AJAX上传功能,你必须设置uploadUrl
属性 -
Enhance plugin to now allow files to be added, appended, removed (based on FEEDBACK from many). Thus one can append files to preview.
增强了插件的实用性,现在可以随意的添加,追加,移除文件(基于回调),所以用户现在可以在预览中追加文件了。 -
New DRAG & DROP zone available in preview to drag and drop files and append.
预览区使用了新的拖曳导入/移除区域,现在可以拖拽添加文件和移除文件了。 -
Delete or upload files one by one OR in batch.
你可以一个一个线性的上传、删除文件或者批量并发的进行上传。 -
If
showPreview
is set to false, or uploadUrl is not supported plugin will degrade to normal form based upload.
该插件会降级成普通的表单当showPreview
属性被设置成false或者上传的url不被该插件所支持的时候 -
Configurable indicators for file awaiting upload, file successfully uploaded, files errored in upload.
可以自定义文件等待上传,成功上传,失败上传时候的指示标志 -
Ability to add extra form data with ajax based uploads.
能够添加基于ajax的其他表单上传 -
Upload progress bar and individual thumbnail upload indicators.
为每个文件添加单独的上传进度条和缩略图、指示标志。 -
Ability to cancel and abort ongoing AJAX uploads.
能够取消和停止正在进行的AJAX上传 -
Build up initial preview content (e.g. gallery of saved images). You can set initial preview actions (prebuilt support for initial preview delete). Other custom action buttons can be set for initial preview thumbnails as well.
增强了初始预览的内容(比如图片画廊)。开发人员可以设置初始预览的动作(现在已经内置了对初始预览删除的支持)其他的初始预览缩略图中的按钮也都可以设置自定义动作。#其实我到现在也没弄明白作者说的initial preview是指的哪块东西 -
Ensure plugin is still lean in size and optimized for performance inspite of the above features by optimally utilizing HTML5 & jquery features only.
通过基于HTML5 和JQuery的优化,该插件在实现上述功能的同时还保持精简的大小和灵活的功能。
-
Automatically refresh preview with content from server as soon as an ajax upload finishes
在ajax上传结束的时候自动的从服务器端刷新预览图的内容
Installation 安装和部署
The plugin can be installed automatically or manually using one of these options:
通过下面的提示,该插件可以手动或自动的安装和部署
Bower Package Manager 包管理器
Installation via bower package manager is as simple as running:使用 bower package manager安装该插件的话只需执行下面这句话这么简单
$ bower install bootstrap-fileinput
Composer Package Manager 包管理器
You can install bootstrap file-input viacomposer
package manager. Either run
你能够通过
composer
包管理器安装该插件
$ php composer.phar require kartik-v/bootstrap-fileinput "dev-master"
or add:
或者添加
"kartik-v/bootstrap-fileinput": "dev-master"
to your composer.json file
到你的composer.json文件
Manual Install 手动安装
You can also manually install the plugin easily to your project. Just download the source ZIP or TAR ball and extract the plugin assets (css and js folders) into your project.
你也能轻松的手动安装该插件到你的项目中去去,只需下载源代码zip或者tar包并且解压插件的内容(css和js文件到你的项目中去即可)
Pre-requisites 依赖
-
Bootstrap 3.x. However, the plugin can be customized for any CSS framework using templates.
Bootstrap 3.x ,但是本插件也能被其他的基于模板的CSS 框架所重新构建 -
Latest JQuery
最新版的JQuery -
Most modern browsers supporting HTML5 file inputs and FileReader API including CSS3 & JQuery.
支持HTML5文件表单和FileReader API 的浏览器 -
For file previews to work, the browser must support the HTML5 FileReaderAPI - else the plugin will auto-degrade to a normal file input. For Internet Explorer, one must use IE versions 10 and above. IE9 and below will work as a normal file input, and will not support multiple file selection or the HTML 5 FileReader API.
浏览器必须支持HTML5 FileReaderAPI才能让文件预览正常的工作,否则该插件会自动降级成一个普通的文件输入框。对于IE浏览器,用户必须使用IE10或以上版本,该插件在IE9及以下版本会降级成一个普通的文件输入框并且不支持选择多个文件。 -
With release 4.0, AJAX uploads are supported. AJAX uploads require that the browser support HTML5 FormData and XHR2 (XMLHttpRequest 2). Most modern browsers support FormData and XHR2. The plugin will automatically degrade to normal form based submission for browsers not supporting AJAX uploads.
在4.0版本中开始支持AJAX上传。AJAX上传需要浏览器支持HTML5 FormData 和 XHR2 (XMLHttpRequest 2),多数浏览器已经支持这两个协议,但是对于不支持AJAX的浏览器该插件会自动降级成一个普通的文件提交表单
Browser-support 浏览器支持
Browser-support 浏览器支持
The plugin uses HTML 5 features to achieve various functionalities. Most modern browsers support these features. However, to know if your browser supports these functions you must run through these checks once below.
该插件使用HTML5来实现被许多浏览器支持的诸多功能。但是想要详细的俩啊哦姐这些浏览器所支持的功能你需要参考下面提供的文档
Functionality功能 | Description描述 | Support支持 |
---|---|---|
File Input Multiple 多文件上传 | Allow users to select multiple files using the native HTML file input. 允许用户使用原生HTML文件输入框选择多个文件 | Browsers |
HTML 5 File API 文件预览和缩略图 | Allow reading and previewing files on the preview pane using the plugin 允许通过该插件读取和预览文件 | Browsers |
HTML 5 XHR2 & FormData AJAX异步上传 | Allow using ajax uploads with ability to append / delete files and track using a progress bar. 允许使用ajax来上传/删除文件并且使用进度条来跟踪进度 | Browsers |
HTML5 Drag Drop 拖曳添加、移除 | Ability to drag and drop files into a dropzone (enabled only for ajax uploads with HTML5 XHR2). 通过拖曳文件到一块区域来添加或者删除文件 | Browsers |
HTML5 Canvas Canvas绘图 | For managing image files via JavaScript. Required if you wish to resize image files before upload. 在上传之前使用JS压缩图片大小 | Browsers |
Usage-modes 使用方式
Largely speaking, the plugin can be configured in one of the following two different modes for upload. IMPORTANT: Do not try to combine the modes below to receive file data as you will receive inconsistent and/or erroneous output.
强调一下,该插件的上传方式能够被配制成下列两种模式的中的某一种,注意不要试图同时使用下列的两种模式,否则你会经常收到错误日志
-
Form Submission: In this mode, you do not set the
uploadUrl
property. The plugin will use the native file input to store files and it can be read after a normal FORM submission (you must envelop the input within a FORM). This is useful for single file uploads OR simpler scenarios of multiple file uploads. Configuration is straightforward as you can read all data POSTED from a native form submission. However, note that the native file input is read only and cannot be modified or updated by external code. Especially for multiple file input selections, ONE cannot append files to an already selected file list. If one tries to select files on an already selected file input, it will overwrite and clear the previous selection. Similarly, one cannot selectively remove/delete files that have been added before upload in this mode.
表单提交:在这种模式下,你不需要设置uploadUrl
属性。本插件会使用原生的文件输入框来存储文件并且会像普通的表单提交一样进行文件的读取(你必须把输入框使用FORM表单包裹起来)。这种方式对于单文件或者简单应用情形下的多文件上传非常有用。你能够从一个原生的表单提交中直接读取所有的发送出去的数据。但是请注意原生的文件输入框是只读的并且不能被外部的代码修改或更新.尤其是对于多文件选择,用户不能像已经选择好的文件列表中追加文件。如果用户试图从一个已经选好的文件输入框中选择文件,那么该文件输入框会被覆盖并清空之前的选择。简单来讲,用户在该种模式下,上传之前不能选择性的移除、删除已添加的文件 -
Ajax Submission: In this mode, you MUST SET the
uploadUrl
property to a VALID ajax processing server action/URL. If theuploadUrl
is set, then the plugin automatically assumes an ajax upload for the scenario. The plugin offers advanced features for ajax submission that is not available in form submission. Features like drag and drop of files, appending/removing files in preview zone, getting a progress bar for your uploads are all possible ONLY IN THIS mode. Your browser must support HTML5 FormData/XHR2 for this to work and your server code that processes the ajax call must return a valid JSON response.
Ajax提交:在这种模式下,你必须将uploadUrl
属性是支撑一个支持ajax的服务端url。当uploadUrl
属性被设置好之后该插件会自动的采取ajax上传方式。在ajax模式提交模式下该插件会提供许多表单模式下没有的先进的功能。比如拖曳添加和移除功能,在预览区中追加、移除文件,并且只有在该种模式下进度条才会生效。你的浏览器必须支持HTML5 FormData/XHR2并且你的服务端代码对于ajax的请求必须返回一个有效的json响应。Note
As an advanced scenario, the plugin allows you to process the ajax upload even if there are no files selected but a validuploadExtraData
is sent with the ajax response. The eventsfilebatchpreupload
,filebatchuploadsuccess
,filebatchuploadcomplete
, orfilebatchuploaderror
will be triggered in this case. It will not have any data for the files selected, but will allow the extra data to be sent.
作为一个先进的方案,该插件允许你处理一个没有选择文件但是仅有一个在ajax响应中被发回的有效的uploadExtraData
属性的ajax上传。filebatchpreupload
,filebatchuploadsuccess
,filebatchuploadcomplete
, orfilebatchuploaderror
- 事件在该种情况下会被触发。虽然没有来自被选择文件的数据,但是还会允许发送一些额外的数据
-
Modes Compared 两种模式的对比 Functionality / Requirement
功能、需求Form Submission
表单提交Ajax Submission
Ajax提交Support single & multiple file upload
支持单文件、多文件上传V V Preview files using HTML 5 FileAPI
使用HTML5预览文件V V Read files directly via form submission
通过表单提交直接读取文件V X Individual file delete icon for each preview thumbnail
为每个预览缩略图添加单独的文件删除标志1 2 Individual file upload icon for each preview thumbnail
为每个预览缩略图添加单独的文件上传标志X V Requires valid JSON response back from server
需要从服务器返回有效的JSON数据X V Requires browser support for HTML5 FormData/XHR2
需要浏览器支持HTML5 FormData/XHR2X V Server code to process ajax and send JSON Response
服务器通过响应码处理ajax并发送JSON响应X V Drag & Drop Files using drop zone
拖曳添加、移除文件X V Ability to append files to already selected list
能够向已选好的列表中追加文件X V Ability to delete files to already selected list
能够在已选好的列表中删除文件1 V Progress bar for uploads
上传进度条X V Read additional form data
读取额外的表单数据Directly via form submit
直接从表单的提交中ViauploadExtraData
使用uploadExtraData属性 -
1 - Via
initialPreviewConfig
(for server uploaded files only).
使用initialPreviewConfig
(仅为服务器上传文件) -
2 - For both server uploaded files (via
initialPreviewConfig
) and client selected files at runtime.
在运行时为服务器上传文件和客户端选择文件(使用initialPreviewConfig 属性)
Usage 用法
Note 提示
The plugin will automatically convert fields of[input type="file"]
to a file input control, if you attach a css class
file
to the input. But, if you are initializing the plugin separately via javascript, then DO NOT ATTACH the css class
file
to the input (as it will result in duplicate initializations and the javascript code maybe skipped).
如果你给这个输入框配置一个css 样式,本插件会自动的将 [input type="file"] 字段转换成一个具备控制功能的文件输入框。但是,如果你使用JS单独的初始化这个插件, 那么就不要再向输入框设置css属性了(否则会导致重复的初始化并且JS代码可能会被覆盖)
Step 1: Load the following assets in your header.
第一步:在你的header中加载如下的资源
- link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
- <link href="path/to/css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />
- <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
- <!-- canvas-to-blob.min.js is only needed if you wish to resize images before upload.
- This must be loaded before fileinput.min.js -->
- <script src="path/to/js/plugins/canvas-to-blob.min.js" type="text/javascript"></script>
- <!-- sortable.min.js is only needed if you wish to sort / rearrange files in initial preview.
- This must be loaded before fileinput.min.js -->
- <script src="path/to/js/plugins/sortable.min.js" type="text/javascript"></script>
- <!-- purify.min.js is only needed if you wish to purify HTML content in your preview for HTML files.
- This must be loaded before fileinput.min.js -->
- <script src="path/to/js/plugins/purify.min.js" type="text/javascript"></script>
- <!-- the main fileinput plugin file -->
- <script src="path/to/js/fileinput.min.js"></script>
- <!-- bootstrap.js below is needed if you wish to zoom and view file content
- in a larger detailed modal dialog -->
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>
- <!-- optionally if you need a theme like font awesome theme you can include
- it as mentioned below -->
- <script src="path/to/js/fa.js"></script>
- <!-- optionally if you need translation for your language then include
- locale file as mentioned below -->
- <script src="path/to/js/<lang>.js"></script>
If you noticed, you need to load the jquery.min.js
and bootstrap.min.css
in addition to the fileinput.min.css
and fileinput.min.js
. The theme file fa.js
can be optionally included for the font awesome icons styling. The locale file .js
can be optionally included for translating for your language if needed.
正如你所见,除了fileinput.min.css
and fileinput.min.js
.两个资源之外,你还需要再导入jquery.min.js
和 bootstrap.min.css
。如果你想要酷炫的icon风格,你可以灵活的添加包含字体的主题文件fa.js
。本地化文件.js
你可以选择自己需要的进行添加来翻译成你需要的语言
Optional Dependent Plugins 可选的插件
-
The
canvas-to-blob.min.js
file is the source for the JavaScript-Canvas-to-Blob plugin by blueimp. It is required to be loaded beforefileinput.min.js
if you wish to use the image resize feature of the bootstrap-fileinput plugin.
canvas-to-blob.min.js 文件是JavaScript-Canvas-to-Blob plugin by blueimp.项目的源文件。如果你想要收缩图片大小的功能的话,它要在fileinput.min.js 之前被加载。
-
The
sortable.min.js
file is the source for the Sortable plugin by rubaxa. It is required to be loaded beforefileinput.min.js
if you wish to sort the thumbnails in the initial preview.
sortable.min.js 文件是Sortable plugin by rubaxa.项目的源文件。如果你想要在初始化预览中根据缩略图进行分类,它需要在fileinput.min.js 加载之前被加载。
-
The
purify.min.js
file is the source for the DomPurify plugin by cure53. It is required to be loaded beforefileinput.min.js
if you wish to purify your HTML for HTML content preview.
purify.min.js 文件是DomPurify plugin by cure53项目的源码,如果你想要为HTML文件的内容预览提供一个格式化的HTML的话,它要在fileinput.min.js 加载之前被加载。
Step 2a: Initialize the plugin on your page. For example,
步骤2a:在你的页面中初始化该插件,举例说明
- // initialize with defaults 默认初始化方法
- $("#input-id").fileinput();
- // with plugin options 使用参数进行初始化
- $("#input-id").fileinput({'showUpload':false, 'previewFileType':'any'});
The #input-id
is the identifier for the input (e.g. type=file
) on your page, which is hidden automatically by the plugin.
#input-id 是input控件默认的id,但是在你的页面上,id被插件自动的隐藏了
Step 2b: Alternatively, you can directly set the plugin options to any input, through HTML 5 data attributes to your input field.
步骤2b:除了上面的做法,你还可以通过HTML5 data属性给任何input直接设置插件的属性
- <input id="input-id" type="file" class="file" data-preview-file-type="text">
Translations 多语言
/js/locales/<lang>.js
after the core
fileinput.min.js
file, where
<lang>
is the language code (e.g.
de
,
fr
etc.). If locale file does not exist, you can submit a translation for the new language via a
new pull request to add to this folder. Check the
sample locale file to copy and create a translation configuration for your own language.
正如用法章节说明的那样,在4.1.8版本之后可以使用多语言的功能。你可以通过在核心JS文件
fileinput.min.js
加载完之后加载一个本地化文件
/js/locales/<语言代码>.js
如果现在的文件列表里没有你的语言的配置,你可以拷贝sample locale file 这个模板文件并为你自己的语言创建一个多语言配置稳健,而且你还还可以向代码仓库发起新的拉去请求来把你自己的语言添加到该项目中。
Ajax Uploads /Ajax上传
You need to setup the server methods to parse and return the right response via AJAX. You can setup uploads in asynchronous OR synchronous modes as described below.
你需要在服务器端部署正确的代码来通过AJAX解析和响应正确JSON数据。你可以像下文描述的一样使用异步或者同步上传方法。
Asynchronous Upload 异步上传
This is the default mode, whereby the uploadAsync
property is set to true
. When uploading multiple files, the asynchronous mode allows triggering parallel server calls for each file upload. You can control the maximum number of files allowed at a time to be uploaded by setting themaxFileCount
property. In asynchronous mode, progress of each thumbnail in the preview is validated and updated.
由于
uploadAsync
这个属性被默认设置成true,所以异步上传是默认模式,当用户上传多个文件时,异步上传模式允许给每个文件触发并发的服务器请求。你能够通过修改maxFileCount
属性设置一次允许最大文件上传数。在异步模式中,预览框里的每个缩略图的进度条都是有效的并且实时更新的。
Receiving Data (on server) 服务器端接收数据
Your server method as set in uploadUrl
receives the following data from the plugin
你的服务器地址应该写在uploadUrl
属性上来接收该插件发送的数据
-
file data: This data is sent to the server in a format very similar to the form file input. For example in PHP you can read this data as
$_FILES['input-name']
, where$_FILES['input-name']
is the name attribute of your input. If you do not set a name attribute for your input, the name is defaulted tofile_data
. Note that multiple file uploads require that you setmultiple
property totrue
for your input. So in PHP you would receive the file data as $_FILES['file_data']
文件数据:这部分数据很像普通的通过表单发送给服务器的数据,以PHP来举例,你可以通过$_FILES['input-name'] 接收这部分数据,input-name 是你input框的name属性。如果你没有给你的input框设置一个name属性,那么它默认为file_data 。注意多文件上传需要你为你的input框设置multiple
属性为true
,并且在PHP端你需要使用 $_FILES['file_data'] 来接收这些文件数据。 -
extra data: The plugin can send additional data to your server method. This can be done by setting
uploadExtraData
as an associative array object in key value pairs. So if you have setupuploadExtraData={id:'kv-1'}
, in PHP you can read this data as$_POST['id']
.
额外数据:本插件能够在发送文件数据之外发送一些额外的数据到你的服务器上。可以通过设置uploadExtraData
属性为一个键值对的数组形式来实现。比如如果你设置uploadExtraData={id:'kv-1'} 那么在PHP端你可以使用$_POST['id'] 来读取这部分文件。 -
Note 注意
In asynchronous mode, you will ALWAYS receive a single FILE on your server action that processes the ajax upload. Basically the plugin will trigger parallel ajax calls for every file selected for upload. You need to write your server upload logic accordingly so that you always read and upload ONE file. Similarly, in the sending data section below, you must return an initialPreview that reflects data only for the single file received.
在异步模式中,你只会经由ajax收到单独的一个一个的文件上传请求。实质上该插件会为每个文件进行并发的ajax上传请求。你需要据此书写你的服务端上传逻辑因为你每个单独请求只会读取和上传一个文件。相似的,如果你参考下面的同步章节来发送数据,你必须返回一个 initialPreview 来反映某个文件是否发送成功了。
Sending Data (from server) 服务端响应规则
Your server method as set in uploadUrl
must send data back as a json encoded object. In this case you can send these 4 pieces of information. Note that in asynchronous mode, you will ALWAYS receive ONE FILE record from the server - so adjust your code accordingly.
你写在uploadUrl
属性上的服务器必须以json格式返回响应。你可以发送如下4种信息,注意在异步模式下你只会从服务器一个一个收到文件响应而不是一次全部返回,所以请据此书写你的服务端代码。
-
error
: string, which will be the error message for the entire batch upload and will help the plugin to identify error in the file upload. For example the response from server would be sent as{error: 'You are not allowed to upload such a file.'}
. Note: The plugin will automatically validate and display ajax exception errors.
error : 字符串,该字段应该包含整个上传过程的错误信息,并将帮助该插件来确认文件上传过程中的错误。举个例子:服务端发送的错误响应应该像{error: 'You are not allowed to upload such a file.'} 注意:本插件会自动的转换为error状态并且显示ajax返回的错误信息。 -
initialPreview
: array, the list of image files or any HTML markup to point to your uploaded files. You will always send ONE row in this array - because you will always receive ONE file with the upload in asynchronous mode. If this property is set, the plugin will automatically replace the files dynamically in the preview content after upload success. The configuration for this is similar to the initialPreview option setting. For example:
initialPreview : 数组, 是指出你上传成功的文件列表或HTML标记。你的数组中应该只有一行和一个元素,因为在异步模式下你每个请求只会收到一个文件。如果这个属性不为空,该插件会自动的在上传成功后修改预览框里的文件状态,这个配置很像initialPreview option setting 举个例子:
- initialPreview: [
- '<img src='/images/desert.jpg' class='file-preview-image' alt='Desert' title='Desert'>',
- ],
-
initialPreviewConfig
: array, the configuration to identify properties for each file markup ininitialPreview
item (that is setup as part ofinitialPreview
). You will always send ONE row in this array - because you will always receive ONE file with the upload in asynchronous mode. If this property is set, the plugin will automatically replace the files dynamically in the preview content after upload success. The configuration for this is similar to the initialPreviewConfig option setting. For example:
initialPreviewConfig
: 数组,是用来识别和标记initialPreview
中字段中的每个文件(这个应该作为initialPreview 配置的一部分)。在异步模式下,你只会收到一个文件的响应。如果该字段不为空,该插件会在文件上传成功后自动的动态替换预览框里的文件状态。这个配置很像initialPreviewConfig option setting 举个例子:
- initialPreviewConfig: [
- {
- caption: 'desert.jpg',
- width: '120px',
- url: 'http://localhost/avatar/delete', // server delete action
- key: 100,
- extra: {id: 100}
- }
- ]
-
initialPreviewThumbTags
: array, an array of objects corresponding to replacing tags within each initial preview thumbnail. The initial preview thumbnails set viainitialPreview
will read this configuration for replacing tags.
initialPreviewThumbTags
:数组,这是用来在每个初始预览缩略图内替换标签所对应的一系列标志,初始预览中的被设置了initialPreview
的缩略图会为替换标签来读取这个配置
- // change thumbnail footer template 修改缩略图底部的模板
- // set initial preview template tags 设置初始化预览的标签模板
- initialPreviewThumbTags:[
- {
- '{CUSTOM_TAG_NEW}': ' ',
- '{CUSTOM_TAG_INIT}': '<span class=\'custom-css\'>CUSTOM MARKUP</span>'
- }
- ];
-
append
: boolean, whether to append the content to the initialPreview if you already set an initialPreview on INIT. If not set this defaults totrue
. If set tofalse
, the plugin will overwrite the initialPreview content.
append
:布尔值,默认为true,来确定是否需要向initialPreview 中添加内容,如果你再INIT中已经设置了一个initialPreview 。如果你设置该属性为false,该插件会覆盖之前的initialPreview 内容。
IMPORTANT
-
You MUST send a valid JSON response from your server, else the upload process will fail. Even if you do not encounter any error, you must at least send an empty JSON object
{}
from your server.
你的服务器端必须返回一个有效的JSON响应,否则即使你没有碰到任何问题,该插件也会提示你上传失败,你至少要从服务器发送一个空JSON 数据如{}
。 -
To trap and display a validation error, your JSON response data must include the
error
key, whose value will be the error HTML markup to display. This is to be setup as mentioned above.
为了捕获和显示一个确定的错误,你的JSON响应必须包含一个error
字段,其值应该是用来显示的HTML格式的报错信息。这个可以像上面提过的一样来设置 -
You can also send in additional keys or data with your JSON response, for you to process them for advanced cases using events like
fileuploaded
.
你也可以在你的JSON响应中发送额外的键值对,而且你还可以通过使用fileuploaded 这类事件来处理这些你自己定义的数据
Synchronous Upload 同步上传
In this mode, the uploadAsync
property is set to false
. This will trigger just one batch upload call to the server and send files from client to server as an array object. Even in this mode, you can control the maximum number of files allowed at a time to be uploaded by setting the maxFileCount
property. However, in synchronous mode, progress will be only at a overall level. Progress of each thumbnail in the preview is not exactly validated and updated. However, the plugin offers you a method of identifying upload errors faced for each file.
在这个模式下,uploadAsync
属性应该被设置成false 。该种模式下客户端的文件会作为一个数组对象发送到服务器,并且只会发送一个批量上传的请求。甚至你可以通过修改maxFileCount
属性的值来限制一次最多上传多少个文件。但是在同步模式下,进度条只会显示一个总体的上传情况,预览区域内的进度条不会很准确并且不会实时更新。但是该插件依然提供你一个识别任何一个文件上传错误的方法。
Receiving Data (on server) 服务端接收数据
Your server method as set in uploadUrl
receives the following data from the plugin
你需要把你的服务器地址设置在uploadUrl
属性中,这样就会收到该插件发送的数据了。
-
file data: This data is sent to the server in a format very similar to the form file input. For example in PHP you can read this data as
$_FILES['input-name']
, whereinput-name
is the name attribute of your input. Also as in asynchronous mode before, if you do not set a name attribute for your input, the name is defaulted tofile_data
. You must set your input name as an array format as mentioned in this web tip, in addition to settingmultiple
property totrue
. If you do not set your input name as an array format, you would receive only the first file on your server. In PHP you would receive the file data as$_FILES['input-name']
, which will be an array of file objects.
文件数据:这部分数据很像普通的通过表单发送给服务器的数据。以PHP为例来说,你可以通过$_FILES['input-name'] 在服务器端读取这些数据,input-name 是你input框的name属性。如果你没有给你的input框设置一个name属性,那么它默认为file_data 。为了设置multiple
属性为ture,你必须把你的输入框名字设置成一个数组的格式如这个web提示中说的那样。如果你没有设置把这个输入框的name设置成一个数组的形式,那么你只会在服务端收到上传的第一个文件。在PHP中你可以用$_FILES['input-name'] 来接受这部分数组数据。 -
extra data: The plugin can send additional data to your server method. This can be done by setting
uploadExtraData
as an associative array object in key value pairs. So if you have setupuploadExtraData={id:'kv-1'}
, in PHP you can read this data as$_POST['id']
.
额外数据:本插件能够在发送文件数据之外发送一些额外的数据到你的服务器上。可以通过设置uploadExtraData
属性为一个键值对的数组形式来实现。比如如果你设置uploadExtraData={id:'kv-1'} 那么在PHP端你可以使用$_POST['id'] 来读取这部分文件
Sending Data (from server)服务端响应规则
In synchronous mode as well, the uploadUrl
must send data back as a json encoded object. In this case you send these 5 pieces of information.
在同步模式下,你写在uploadUrl
属性中的服务端必须返回一个JSON格式的响应,你可以在其中发送下面5条信息
-
error
: string, which will be the error message for the entire batch upload and will help the plugin to identify error in the file upload.
error : 字符串,其值应该是整个批量上传的过程的错误信息,并且这个信息会帮助该插件定位文件上传中的错误 -
errorkeys
: array, the keys (zero-based indexes for the file data received) for the files that have errored out. Based on this data, the plugin will automatically set the thumbnails and each individual preview file to error out.
errorkeys :数组,这些键(下标从0开始)应该包含上传文件的错误信息。该插件会根据这些数据自动的设置修改缩略图和每个文件单独的预览图来输出错误信息 -
initialPreview
: array, the list of image files or any HTML markup to point to your uploaded files. If this property is set, the plugin will automatically replace the files dynamically in the preview content after upload success. The configuration for this is similar to theinitialPreview option setting. For example:
initialPreview:数组,一些列的图片文件或者HTML标记来指出你上传成功了的文件。如果该属性不为空,该插件会在上传成功之后自动的替换那些文件的动态预览。该配置很像initialPreview option setting 举个例子- initialPreview: [
- '<img src='/images/desert.jpg' class='file-preview-image' alt='Desert' title='Desert'>',
- '<img src='/images/jellyfish.jpg' class='file-preview-image' alt='Jelly Fish' title='Jelly Fish'>',
- ],
-
initialPreviewConfig
: array, the configuration to identify properties for each file markup ininitialPreview
item (that is setup as part ofinitialPreview
). If this property is set, the plugin will automatically replace the files dynamically in the preview content after upload success. The configuration for this is similar to the initialPreviewConfig option setting. For example:
initialPreviewConfig:数组,这个配置用来识别initialPreview
项目中每个文件标记的属性。如果这个字段不为空,该插件会自动的在文件上传成功后动态的替换预览图内容。该配置很像initialPreviewConfig option setting 举个例子- initialPreviewConfig: [
- {
- caption: 'desert.jpg',
- width: '120px',
- url: 'http://localhost/avatar/delete', // server delete action
- key: 100,
- extra: {id: 100}
- },
- {
- caption: 'jellyfish.jpg',
- width: '120px',
- url: 'http://localhost/avatar/delete', // server delete action
- key: 101,
- extra: function() {
- return {id: $('#id').val()};
- },
- }
- ]
-
initialPreviewThumbTags
: array, an array of objects corresponding to replacing tags within each initial preview thumbnail. The initial preview thumbnails set viainitialPreview
will read this configuration for replacing tags.
initialPreviewThumbTags:数组,一个关于初始化预览图中缩略图标签的对象的数组。由initialPreview
定义的初始化预览图的缩略图将会读取这个配置来替换标签- // change thumbnail footer template 修改缩略图footer的模板
- // set initial preview template tags 设置初始化预览图的tag模板
- initialPreviewThumbTags:[
- {
- '{CUSTOM_TAG_NEW}': ' ',
- '{CUSTOM_TAG_INIT}': '<span class=\'custom-css\'>CUSTOM MARKUP 1</span>'
- },
- {
- '{CUSTOM_TAG_NEW}': ' ',
- '{CUSTOM_TAG_INIT}': '<span class=\'custom-css\'>CUSTOM MARKUP 2</span>'
- }
- ];
-
append
: boolean, whether to append the content to the initialPreview if you already set an initialPreview on INIT. If not set this defaults totrue
. If set tofalse
, the plugin will overwrite the initialPreview content.
append:布尔值,如果你在INIT已经设置了一个initialPreview,是否向initialPreview 中追加内容 。该属性的默认值为true。如果把它设为false 那么该插件会覆盖原来的initialPreview 内容。
For example the response from server would be sent as {error: 'You have faced errors in 4 files.', errorkeys: [0, 3, 4, 5]}
. Note: The plugin will automatically validate and display ajax exception errors.
举个例子,服务器的响应可以像这样:{error: 'You have faced errors in 4 files.', errorkeys: [0, 3, 4, 5]} 注意,该插件会自动的检验和显示ajax异常信息。
IMPORTANT
-
You MUST send a valid JSON response from your server, else the upload process will fail. Even if you do not encounter any error, you must at least send an empty JSON object
{}
from your server.
你的服务器端必须返回一个有效的JSON响应,否则即使你没有碰到任何问题,该插件也会提示你上传失败,你至少要从服务器发送一个空JSON 数据如{}
。 -
To trap and display a validation error, your JSON response data must include the
error
key, whose value will be the error HTML markup to display. In addition, you must typically also send theerrorkeys
for synchronous mode to identify the keys for files which faced errors. This is to be setup as mentioned above.
为了捕获和显示一个确定的错误,你的JSON响应必须包含一个error
字段,其值应该是用来显示的HTML格式的报错信息。另外在同步模式中你必须发送errorkeys
字段来区分到底哪个文件遇到了异常。这个可以像上面提过的一样来设置
-
You can also send in additional keys or data with your JSON response, for you to process them for advanced cases using events like
filebatchuploadsuccess
.
你也可以在你的JSON响应中发送额外的键值对,而且你还可以通过使用filebatchuploadsuccess
这类事件来处理这些你自己定义的数据
Options 附加选项
The plugin supports these following options:
该插件支持如下的附加选项
language 多语言
string, language configuration for the plugin to enable the plugin to display messages for your locale (you must set the ISO code for the language). You can have multiple language widgets on the same page. The locale JS file for the language code must be defined as mentioned in the translations section. The file must be loaded after fileinput.js
.
字符串,一项使该插件为你当地显示相应消息的配置(你必须为你的语言设置ISO码,如zh,en)。你可以在同一个页面上配置多种语言。本地的语言码JS文件必须按照上面多语言章节进行定义,该文件会在fileinput.js 加载完之后开始加载。
theme 主题
string, theme to use for the plugin (will default to the inbuilt theme if not set). With release v4.3.2, the fileinput plugin supports advanced theming and ability to have separate themes for multiple widgets on the same page. To do this, follow these simple steps:
字符串,是该插件使用的主题(默认是内置主题)。在4.3.2版本中,该插件支持更先进的主题并且能够为同一页面的多个控件设置不同的主题
-
Load respective theme JS file(s) that you need (e.g.
themes/fa/fa.js
for Font Awesome theme). The theme file(s) must be loaded after thefileinput.js
.
根据你的需要加载每个JS各自的主题(如Font Awesome的主题配置themes/fa/fa.js
)。主题文件必须在fileinput.js 加载完毕之后再加载。 -
Set the
theme
property in the plugin to the theme you need and which you have setup in your theme configuration JS file above (e.g.'fa'
).
用上面提到的已经在你的主题配置文件中配置好的JS文件,在该插件中设置theme
属性为你需要的主题 -
The plugin will automatically read the theme configuration for the theme name from
$fileinputThemes['<theme-name>']
from the JS file (e.g. via$fileinputThemes['<theme-name>']
).
该插件会自动的根据$fileinputThemes['<theme-name>'] 标注的主题文件名字去从JS文件读取相应的主题配置文件
-
The plugin will automatically also prepend the CSS selector
theme-<theme-name>
to the file input container, so that you can override your styles. The CSS for such themes can be submitted by community inthemes/THEME_NAME
folder of the repo.
该插件也会自动的在文件上传容器中伪装CSS选择器theme-<theme-name>
,所以你可以覆盖你的风格。这些CSS主题会被社区提交到代码库的themes/THEME_NAME 文件夹。 -
You can additionally load any theme specific CSS files if needed.
如果需要,你可以额外添加任何特定主题CSS文件
Note
Currently the plugin includes the Font Awesome and Glyphicons themes. More advanced themes may be added in future or can be contributed here by the community.目前,该插件包含了 Font Awesome 和Glyphicons 的主题,更多先进的会在以后加入,或者会被社区所贡献。
showCaption
boolean whether to display the file caption. Defaults to true
.
showPreview
boolean whether to display the file preview. Defaults to true
.
showRemove
boolean whether to display the file remove/clear button. Defaults to true
.
showUpload
boolean whether to display the file upload button. Defaults to true
. This will default to a form submit button, unless the uploadUrl is specified.
showCancel
boolean whether to display the file upload cancel button. Defaults to true
. This will be only enabled and displayed when an AJAX upload is in process.
showClose
boolean whether to display the close icon in the preview. Defaults to `true`. This will be only parsed when showPreview
is true or when you are using the{close}
tag in your preview templates.
showUploadedThumbs
boolean whether to persist display of the uploaded file thumbnails in the preview window (for ajax uploads) until the remove/clear button is pressed. Defaults to true
. When set to false
, a next batch of files selected for upload will clear these thumbnails from preview.
showBrowse
boolean whether to display the file browse button. Defaults to true
.
browseOnZoneClick
boolean whether to enable file browse/select on clicking of the preview zone. Defaults to false
.
autoReplace
boolean whether to automatically replace the files in the preview after the maxFileCount
limit is reached and a new set of file(s) is/are selected. This will only work if a valid maxFileCount
is set. Defaults to false
.
captionClass
string, any additional CSS class to append to the caption container.
previewClass
string, any additional CSS class to append to the preview container.
mainClass
string, any additional CSS class to append to the main plugin container that will render the caption and the browse, remove, and upload buttons. Defaults to file-caption-main
.
purifyHtml
boolean, whether to purify HTML content displayed for HTML content type in preview. Defaults to true
. This functionality will need the DomPurify plugin by cure53 to be loaded.
fileSizeGetter
boolean, the callback to generate the human friendly filesize based on the bytes
parameter. If not set this will default to the following callback:
- function (bytes) {
- var i = Math.floor(Math.log(bytes) / Math.log(1024)),
- sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
- return (bytes / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
- }
initialPreview
string | array the initial preview content to be displayed. You can pass the minimal HTML markup for displaying your image, text, or file. If set as a string, this will display a single file in the initial preview if there is no delimiter. You can set a delimiter (as defined in initialDelimiter
) to show multiple files in initial preview. If set as an array, it will display all files in the array as an initial preview (useful for multiple file upload scenarios).
The following CSS classes will need to be added for displaying each file type as per the plugin style theme:
- image files: Include CSS class
file-preview-image
- text files: Include CSS class
file-preview-text
- other files: Include CSS class
file-preview-other
Examples of how you can setup various files for initial preview:
- // for image files
- initialPreview: [
- "<img src='/images/desert.jpg' class='file-preview-image' alt='Desert' title='Desert'>",
- "<img src='/images/jellyfish.jpg' class='file-preview-image' alt='Jelly Fish' title='Jelly Fish'>",
- ],
- // for text files
- initialPreview: "<div class='file-preview-text' title='NOTES.txt'>" +
- "This is the sample text file content upto wrapTextLength of 250 characters" +
- "<span class='wrap-indicator' οnclick='$(\"#show-detailed-text\").modal(\"show\")' title='NOTES.txt'>[…]</span>" +
- "</div>"
- // for other files
- initialPreview: "<div class='file-preview-text'>" +
- "<h2><i class='glyphicon glyphicon-file'></i></h2>" +
- "Filename.xlsx" + "</div>"
i
html端调用实例:
<div class="form-group">
<label for="exampleInputEmail1">商品图片(最多可上传4张jpg格式的图片)</label>
<input id="file-1" type="file" multiple class="file" data-overwrite-initial="false" data-max-file-count="4" name="haha" ">
</div>
然后在js里这么写
$("#file-1").fileinput({//这里的id是input标签的id
uploadUrl: 'servlet/UploadImgServlet', // you must set a valid URL here else you will get an error
allowedFileExtensions : ['jpg', 'png','gif'],//允许的文件类型
overwriteInitial: false,
maxFileSize: 1000,//文件的最大大小
maxFilesNum: 10,//最多文件数量
//allowedFileTypes: ['image', 'video', 'flash'],
slugCallback: function(filename) {
return filename.replace('(', '_').replace(']', '_');
}
});
一定要注意本插件在ajax异步上传多个文件时是分批多次上传的,一次只上传一个文件,然后上传多次,所以在servlet里面判断第几个文件是没有作用的
但是ajax同步模式上传发来的是一个文件数组,可以拿到文件的索引
下面提供一种在servlet端接收文件并存储的代码最短小的写文件方式:
以下代码可以接受大于2m的文件,需要先导入两个jar包
1) commons-fileupload-1.2.2-bin.zip : 点击打开链接
2) commons-io-2.3-bin.zip : 点击打开链接
注意里面用到的类如果可以选择应选择apache-common包里面的package com.situ.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
public class UploadImgServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获得磁盘文件条目工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//获取文件缓存文件夹的路径
String tempPath = request.getRealPath("/temp");
//如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
//设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
/**
* 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上,
* 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的
* 然后再将其真正写到 对应目录的硬盘上
*/
File tempFolder = new File(tempPath);
if(tempFolder.exists()==false){
tempFolder.mkdirs();
}
//设置缓存文件夹
factory.setRepository(new File(path));
//设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
factory.setSizeThreshold(1024*1024) ;
//高水平的API文件上传处理
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> list = null;
try {
list = (List<FileItem>)upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(FileItem item : list)
{
//获取表单的属性名字
String name = item.getFieldName(); //这个name就是<input>标签中的name属性,是很重要与服务器通信的方式
System.out.println("传来的filedName是"+name);
//如果获取的 表单信息是普通的 文本 信息
if(item.isFormField())
{
System.out.println(item);
}
//对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
else
{
/**
* 以下三步,主要获取 上传文件的名字
*/
//获取路径名
String value = item.getName() ;
//索引到最后一个反斜杠
int start = value.lastIndexOf("\\");
//截取 上传文件的 字符串名字,加1是 去掉反斜杠,
String filename = value.substring(start+1);
//将文件写入服务器,第二个参数是文件名(不要加扩展名),第三个参数是要写入的文件夹 ,一般在这里文件名用随机数生成比较好
writeFile(item, filename, "item_imgs");
}
}
PrintWriter out = response.getWriter();
out.print("{}");//返回空json字符串代表上传成功,同时在浏览器收到后会出现绿色的对勾,如果失败就传输一个"{error:'错误信息'}",这样的话进图条就走不到100%并且还会锁死
out.flush();
out.close();
}
/**
* 传入一个fileitem,并且按照给出的文件名前缀,文件名后缀(索引),文件存储相对目录来写入从互联网的到的文件
* @param fileItem 传来的文件对象
* @param firstName 文件名前缀
* @param parentFolder 相对存储目录,如:"imgs" 根目录C:\apache-tomcat-7.0.61\webapps\项目名\+parentFolder\
* @return
* @throws IOException
*/
public boolean writeFile(FileItem fileItem,String firstName,String parentFolder) throws IOException{
//用原来的文件名做文件名,用项目目录的绝对地址/attachment作为目录地址
File file1 = new File(this.getServletContext().getRealPath(parentFolder+"/"),firstName+".jpg");//自动补后面扩展名为jpg
if(file1.getParentFile().exists()==false){
file1.getParentFile().mkdirs();
}
file1.createNewFile();
InputStream ins = fileItem.getInputStream();
OutputStream ous = new FileOutputStream(file1);
try{
byte[] buffer = new byte[1024];
System.out.println("开始写文件");
int len = 0;
while((len = ins.read(buffer)) > -1)
ous.write(buffer,0,len);
System.out.println("已保存的文件"+file1.getAbsolutePath());
}finally{
ous.close();
ins.close();
}
return true;
}
}
参考文章:http://blog.csdn.net/hzc543806053/article/details/7524491