最近做文件上传,使用了jquery-uploadify插件,用的是官网最新的3.2版本,官网地址:http://www.uploadify.com/download/
在这里建议下:在面对最新的版本的时候,最好是去它的官网查看文档,同时借鉴下别人写的旧版本的使用心得,这样就能快速的上手了,好了,言归正传,let's go
解压下载的文件到任意一个目录下面,文件夹名称为uploadify,最好是自己重命名一下,在后面加上版本号;文件内容如下
官方给的是php的示例,这里我用的java所以就不看了,直接删了只留下以下文件:
接下来就是如何使用了,首先,在页面加入引用,主要是三个文件,一个是jquery必不可少的,另外两个就是插件文件夹下面的了,这个插件文件夹可以拷贝到自己的项目路径下,如我的就是在项目根目录下的js文件里面,同时要在根目录下面建立一个img文件夹,将上图中的uploadify-cancel.png图片放进去,这样子可以解决插件取消文件队列报错找不到图片的错误
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<link rel="stylesheet" type="text/css" href="./js/uploadify/uploadify.css">
<script type="text/javascript" src="./js/uploadify/jquery.uploadify.js"></script>
这里图片路径一定要是对的,还有一个要注意的问题就是jquery冲突 问题,在很多时候做页面的时候,我们都是喜欢引入头部,底部两个页面,问题就在这里,如果你的主页面也就是需要用到插件的页面引入了这两个页面的话,必须保证这两个页面中没有引入多余的jquery.js文件,不然就会导致出现$(..).uploadify not a function 的错误。切记,这是我亲自尝过的苦啊。
接下来就是渲染上传按钮的操作了,代码如下:
页面HTML
<tr>
<td class="align_right">
<em><font color="red">*</font></em>
<label>上传写真照</label>
</td>
<td class="input_style">
<div class="upload_div">
<input id="upload_photo" class="upload_button" type="button" value="本地上传"/>
<input type="hidden" id="userPhoto" name="userPhoto"/>
<div id="photo_queue"></div>
<p>最多上传10张照片,尺寸480*800,格式jpg或png可批量上传</p>
</div>
</td>
</tr>
JS文件
$("#upload_photo").uploadify({
//按钮额外自己添加点的样式类.upload
'buttonClass' : 'upload',
//限制文件上传大小
'fileSizeLimit' : '2MB',
//文件选择框显示
'fileTypeDesc' : '选择图片',
//文件类型过滤
'fileTypeExts' : '*.jpg;*.png',
//按钮高度
'height' : '30',
//按钮宽度
'width' : '100',
//请求类型
'method' : 'post',
//是否支持多文件上传
'multi' : true,
//需要重写的事件
'overrideEvents' : ['onDialogClose','onSelectError','onUploadError'],
//队列ID,用来显示文件上传队列与进度
'queueID' : 'photo_queue',
//队列一次最多允许的文件数,也就是一次最多进入上传队列的文件数
'queueSizeLimit' : 10,
//上传动画,插件文件下的swf文件
'swf' : './js/uploadify/uploadify.swf',
//处理上传文件的服务类
'uploader' : '/UploadFileServlet?type=photo&uploadPath=' + userId + '\\' + appId,
//上传文件个数限制
'uploadLimit' : 10,
//上传按钮内容显示文本
'buttonText' : '图片上传',
//自定义重写的方法,文件上传错误触发
'onUploadError' : uploadify_onUploadError,
//文件选择错误触发
'onSelectError' : uploadify_onSelectError,
//文件队列上传完毕触发
'onQueueComplete' : heightReset,
//队列开始上传触发
'onUploadStart' : heightFit,
//单个文件上传成功触发
'onUploadSuccess' : function(file, data, response){
$("#userPhoto").attr("value",data);
//恢复原始高度
}
});
这里有个小问题就是:'queueSizeLimit' 和 'uploadLimit'这两个参数配置的效果是一样的,而且哪个配置的小,就是按照哪个来的,也就是说想通过插件来实现限制上传文件个数是不现实的,这个必须结合后台程序才能限制总的文件上传个数。可以在'onUploadStart'中通过ajax请求后台程序,返回文件个数,然后在做相应的处理
后台处理文件上传服务类:
public Map<String, String> uploadPackage(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//使用apache开源组织下的commons-fileupload-1.2.jar组件做文件上传
String projectPath = PathTool.getWebRootPath();
String tempPath = projectPath + "uploadFile/temp";
Map<String, String> params = new HashMap<String, String>();
try
{
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置文件缓冲区大小
factory.setSizeThreshold(1024 * 1024);
//超过缓冲区大小,临时文件放在什么地方
factory.setRepository(new File(tempPath));
//2、使用文件上传工厂,创建一个文件上传的servlet对象;解析表单,保存到list里面
ServletFileUpload upload = new ServletFileUpload(factory);
//允许上传的大小,以字节为单位
upload.setFileSizeMax(1024 * 1024 * 1024);
//设置编码格式
upload.setHeaderEncoding("UTF-8");
// 得到所有的表单域,它们目前都被当作FileItem
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
// 依次处理请求
while (iter.hasNext())
{
FileItem item = iter.next();
if (item.isFormField())
{ // 如果是普通的表单域
/* "处理普通表单内容 ... */
String name = item.getFieldName();
String value = new String(item.getString().getBytes("ISO-8859-1"), "utf-8");
params.put(name, value);
}
else
{ /* 如果是文件上传表单域 */
// 1.获取文件名
String fileName = item.getName();
String fieldName = item.getFieldName(); //文件域名称
String contentType = item.getContentType(); //文件类型
if (fileName != null & !"".equals(fileName))
{
System.out.println("文件域名称:" + fieldName + "\n文件名:" + fileName + "\n文件类型:" + contentType);
//获取文件后缀名
String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
// 2.先将上传文件保存到本地硬盘上
ServletContext context = this.getServletContext();
String dir = "";
//=======将上传的文件存放到服务器的专门的文件夹下:uploadfile============
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
fileName = sdf.format(date) + fileName;
//这里判断文件类型
//以应用id做为文件夹分类
if("png".equals(suffix) || "jpg".equals(suffix)){
dir = context.getRealPath("uploadFile/photo/");
}
if("mp3".equals(suffix)){
dir = context.getRealPath("uploadFile/music/");
}
dir += appId;
System.out.println(dir);
File file = new File(dir,fileName);
//当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件
file.createNewFile();
// 获得流,读取数据写入文件
InputStream in = item.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
int len = 0;
byte[] buffer = new byte[1024];
// 3.获取本地文件的绝对路径
while ((len = in.read(buffer)) > 0){
fos.write(buffer, 0, len);
}
// 关闭资源文件操作
fos.close();
in.close();
// 删除临时文件
item.delete();
//new FtpUploadThread(filepath, "handbb_down", fileName).run();
//这里判断是图片还是mp3文件
if("png".equals(suffix) || "jpg".equals(suffix)){
photo += fileName + ",";
}
if("mp3".equals(suffix)){
music += fileName + ",";
}
// 7.删除本地文件
//file.delete();
}
else
{// 修改操作时,如果没有上传文件
// if("icon_url".equalsIgnoreCase(fieldName)){
// }
// if("download_url".equalsIgnoreCase(fieldName)){
// }
}
}
}
params.put("photo", photo);
params.put("music", music);
}
catch (Exception e)
{
e.printStackTrace();
}
return params;
}
好了,基本的使用方法就到这里了