jQuery上传文件控件Uploadify使用
Uploadify是JQuery的一个上传插件,支持ajax无刷新上传,多个文件同时上传,上传进行进度显示,删除已上传文件等。
首先应下载jQuery和uploadify插件
jQuery下载地址:http://www.jq22.com/jquery-info122
Uploadify下载地址:http://www.uploadify.com/,点击Flash Version
jsp页面需要引入:
<script src="<%=basePath%>resources/js/jquery-2.1.4/jquery.min.js"></script>
<script src="<%=basePath%>resources/js/uploadify/jquery.uploadify.min.js"></script>
<link type="text/css" rel="stylesheet" href="<%=basePath%>resources/js/uploadify/uploadify.css">
html代码:
<div>
<input type="file" name="uploadify" id="uploadFile" />
<div id="some_file_queue"></div>
<div id="fileName"></div>
<div style="clear: both;margin-top: 20px;cursor: pointer;">
<a
class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary a-btn"
onclick="javascript:$('#uploadFile').uploadify('upload','*')">
<span class="glyphicon glyphicon-play"></span> <span
class="ui-button-text">开始上传</span>
</a><a
class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary a-btn"
onclick="javascript:$('#uploadFile').uploadify('cancel','*')">
<span class="glyphicon glyphicon-ban-circle"></span> <span
class="ui-button-text">取消上传</span>
</a>
</div>
</div>
js代码:
$(function() {
$("#uploadFile").uploadify({
'swf' : '<%=basePath%>resources/js/uploadify/uploadify.swf',
'uploader' : '<%=basePath%>file/uploadFile', //服务器端方法
//'formData' : {'someKey' : 'someValue', 'someOtherKey' : 1},//传输数据json格式
'height' : 30, //按钮高度
'width' : 100, //按钮宽度
'fileObjName' : 'uploadify',//默认 Filedata, $_FILES控件name名称
'multi' : true, //设置是否允许一次选择多个文件,true为允许,false不允许
'auto' : false, //是否自动上传
'buttonText' : '选择文件',//按钮显示文字
//'buttonClass' : 'uuid', //按钮辅助class
'buttonCursor' : 'hand', //设置鼠标移到按钮上的开状,接受两个值'hand'和'arrow'(手形和箭头)
'debug' : false, //开启或关闭debug模式
'cancelImg' : '<%=basePath%>resources/js/img/uploadify-cancel.png', //这个没测试出来,默认是放在与uploadify同级的img文件夹下
'fileTypeExts' : '*.jpg;*.jpge;*.gif;*.psd;*.png;*.txt;*.doc;*.docx;*.ppt;*.pptx;*.pdf', //文件后缀限制 默认:'*.*'
'fileSizeLimit' : '10MB',//接受一个单位(B,KB,MB,GB)。如果是数字则默认单位为KB。设置为0时表示不限制
'fileTypeDesc' : 'All Files',//可选文件的描述。这个值出现在文件浏览窗口中的文件类型下拉选项中。(chrome下不支持,会显示为'自定义文件',ie and firefox下可显示描述)
'method' : 'post', //提交上传文件的方法,接受post或get两个值,默认为post
'progressData' : 'percentage',//设置文件上传时显示数据,有‘percentage’ or ‘speed’两个参数(百分比和速度)
'queueID' : 'some_file_queue',//设置上传队列DOM元素的ID,上传的项目会增加进这个ID的DOM中。设置为false时则会自动生成队列DOM和ID。默认为false
'queueSizeLimit' : 5,//一个队列上传文件数限制
'simUploadLimit' : 5, //一次同步上传的文件数目
'removeCompleted' : true, //完成时是否清除队列 默认true
'removeTimeout' : 1, //完成时清除队列显示秒数,默认3秒
'requeueErrors' : false, //设置上传过程中因为出错导致上传失败的文件是否重新加入队列中上传
'successTimeout' : 30, //设置文件上传后等待服务器响应的秒数,超出这个时间,将会被认为上传成功,默认为30秒
'uploadLimit' : 99, //允许上传的最多张数
'onUploadSuccess' : function(file, data, response) { //上传成功
var jdata = $.parseJSON(data);
$("#fileName").append("<p><em name='fileName' onclick = 'downLoadFile(this)' style='color:#555555'>"+jdata.fileName+"</em><em style='color:red' onclick = 'deleteFile(this)'>删除</em><a name='filePath' style='display:none'>"+jdata.filePath+"</a></p>");
console.log( 'id: ' + file.id
+ ' - 索引: ' + file.index
+ ' - 文件名: ' + file.name
+ ' - 文件大小: ' + file.size
+ ' - 类型: ' + file.type
+ ' - 创建日期: ' + file.creationdate
+ ' - 修改日期: ' + file.modificationdate
+ ' - 文件状态: ' + file.filestatus
+ ' - 服务器端消息: ' + data
+ ' - 是否上传成功: ' + response);
},
'onFallback':function(){
alert("您未安装FLASH控件,无法一次性上传多个文件!请安装FLASH控件后再试。");
},
onSelectError:function(file, errorCode, errorMsg){ //选择失败
switch(errorCode) {
case -100:
alert("上传的文件数量已经超出系统限制的"+$('#uploadFile').uploadify('settings','queueSizeLimit')+"个文件!");
break;
case -110:
alert("文件 ["+file.name+"] 大小超出系统限制的"+$('#uploadFile').uploadify('settings','fileSizeLimit')+"大小!");
break;
case -120:
alert("文件 ["+file.name+"] 大小异常!");
break;
case -130:
alert("文件 ["+file.name+"] 类型不正确!");
break;
}
},
/* //上传汇总
'onUploadProgress' : function(file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
$('#progress').html(totalBytesUploaded + ' bytes uploaded of ' + totalBytesTotal + ' bytes.');
},
'onUploadComplete' : function(file) { //上传完成
console.log('The file ' + file.name + ' finished processing.');
},
//修改formData数据 ,每个文件即将上传前触发
'onUploadStart' : function(file) {
$("#uploadFile").uploadify("settings", "someOtherKey", 2);
},
//删除时触发
'onCancel' : function(file) {
alert('The file ' + file.name + '--' + file.size + ' was cancelled.');
},
//清除队列
'onClearQueue' : function(queueItemCount) {
alert(queueItemCount + ' file(s) were removed from the queue');
},
//调用destroy是触发
'onDestroy' : function() {
alert('我被销毁了');
},
//每次初始化一个队列是触发
'onInit' : function(instance){
alert('The queue ID is ' + instance.settings.queueID);
},
//上传错误
'onUploadError' : function(file, errorCode, errorMsg, errorString) {
alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
}, */
});
});
页面展示:
后台代码:
上传方法
@RequestMapping("/uploadFile")
public void uploadFile(
@RequestParam(value = "uploadify", required = false) MultipartFile file,
HttpServletRequest request, HttpServletResponse response) throws IOException {
String fileName = file.getOriginalFilename();
Map<String, Object> dataMap = new HashMap<String, Object>();
//本机测试路径
String path = request.getSession().getServletContext().getRealPath("files");
String uuid = UUID.randomUUID().toString();
String filePath = uuid + fileName.substring(fileName.lastIndexOf("."));
File targetFile = new File(path, filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
file.transferTo(targetFile);
dataMap.put("filePath", filePath);
dataMap.put("fileName", fileName);
logger.info("文件上传成功");
} catch (Exception e) {
logger.error(e.getMessage());
}
ObjectMapper mapper = new ObjectMapper();
String data =mapper.writeValueAsString(dataMap);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print(data);
}
下载方法
@RequestMapping("/downLoadFile")
public void downLoadFile(HttpServletRequest req,HttpServletResponse resp,FileDTO fileDTO) throws IOException{
logger.info("/file/downLoadFile");
PrintWriter pw = null;
resp.setContentType("text/html,charset=utf-8");
resp.setCharacterEncoding("UTF-8");
try {
String path = req.getSession().getServletContext().getRealPath("/files")+ File.separator +fileDTO.getFilePath();
File dir = new File(path);
if (!dir.exists()) {
pw=resp.getWriter();
pw.print("<script>alert('抱歉,文件不存在');location.href='javascript:history.go(-1)';</script>);");
return;
}
FileInputStream in = new FileInputStream(path);
OutputStream fos = resp.getOutputStream();
resp.reset();
resp.setContentType("application/x-download");
resp.setHeader("Content-disposition", "attachment;filename="+getFileName(req,fileDTO.getFileName()));
byte[] b = new byte[2048];
int read;
while ((read = in.read(b)) != -1) {
fos.write(b,0,read);
}
fos.flush();
in.close();
fos.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
pw=resp.getWriter();
pw.print("<script>alert('抱歉,文件下载失败');location.href='javascript:history.go(-1)';</script>);");
}
}
public String getFileName(HttpServletRequest req,String channelFileName) throws UnsupportedEncodingException{
String fileName="";
String userAgent = req.getHeader("User-Agent");
//针对IE或者以IE为内核的浏览器,加上win10自带的Edge浏览器
if (userAgent.contains("MSIE")||userAgent.contains("Trident")||userAgent.contains("Edge")) {
fileName = java.net.URLEncoder.encode(channelFileName, "UTF-8");
} else {
//非IE浏览器的处理:
fileName = new String(channelFileName.getBytes("UTF-8"),"ISO-8859-1");
}
return fileName;
}
package com.cn.entity;
import java.io.Serializable;
public class FileDTO implements Serializable{
/**
*
*/
private static final long serialVersionUID = -2487063172455865142L;
private int id;
private String fileName;
private String filePath;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
jQuery上传文件控件Uploadify使用的更多相关文章
- jquery上传文件控件Uploadify
基于jquery的文件上传控件,支持ajax无刷新上传,多个文件同时上传,上传进行进度显示,删除已上传文件. 要求使用jquery1.4或以上版本,flash player 9.0.24以上. 有两个 ...
- 兼容IE浏览器样式的html上传文件控件
最近在公司做项目时需要用到html的上传文件控件,但发现原生的上传文件控件<input type="file" />在IE.Chrome浏览器的显示效果相差很大,为了统 ...
- html+css上传文件控件美化
html上传美化: <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...
- asp.net 页面上传文件控件后台代码Request.Files获取不到
今天开发中遇到页面文件上传控件选择了文件,而后台Request.Files.Count取值为0,之前开发中遇到过几次,老是忘掉,今天记下来. html: <input type="fi ...
- ASP.NE 上传文件控件
protected void Button1_Click(object sender, EventArgs e) { //if (Request["id"]==null & ...
- 用JS怎么判断上传文件控件是否未选择文件
页面代码: <form name="form1" action="uploadPosdetailFile.html" method="post& ...
- JQuery上传文件插件Uploadify使用笔记
新工作的第一份任务就是给实现 限制Uploadify 上传文件格式为图片 测试出来报错,选择了非图片文件,提示错误后,再选择其他文件,上传时还是包含了之前清空的非图片文件 最后实现效果的代码是 //上 ...
- Webform之FileUpload(上传按钮控件)简单介绍及下载、上传文件时图片预览
1.FileUpload上传控件:(原文:http://www.cnblogs.com/hide0511/archive/2006/09/24/513201.html) FileUpload 控件显示 ...
- JQuery 上传文件插件 Uploadify1
基于jquery的文件上传控件,支持ajax无刷新上传,多个文件同时上传,上传进行进度显示,删除已上传文件. <link href="~/Content/themes/uploadif ...
随机推荐
- MySQL报错:Packets larger than max_allowed_packet are not all
MySQL根据配置文件会限制Server接受的数据包大小.有时候大的插入和更新会受 max_allowed_packet 参数限制,导致写入或者更新失败. 修改方法: 1.修改配置文件my.ini m ...
- Ionic+AngularJS 开发的页面在微信公众号下显示不出来原因查究
ionic 页面 微信浏览器遇到的坑 公司的微信公众号一部分页面是用AngularJS+Ioinc开发,发现在本地浏览器测试的时候都没问题,传到服务器在微信公众号下跑就出问题来,经查是: index- ...
- leetcode 141、Linked list cycle
一种方法是用set存储出现过的指针,重复出现时就是有环: class Solution { public: bool hasCycle(ListNode *head) { set<ListNod ...
- react及flux架构范例Todomvc分析
react及flux架构范例Todomvc分析 通过分析flux-todomvc源码,学习如何通过react构建web程序,了解编写react应用程序的一般步骤,同时掌握Flux的单向数据流动架构思想 ...
- WIN7如何在任务栏建立我的电脑的快捷图标
1. 在桌面空白处鼠标右击->新建->快捷方式,在弹出的对话框中输入 %SystemRoot%\explorer.exe /E,::{20D04FE0-3AEA-1069-A2D8-08 ...
- 字符串处理,Poj(2121)
题目链接:http://poj.org/problem?id=2121 差一点就WA哭了,主要是自己傻逼了. 思路: 遇到hundred,sum*100; 但是遇到thouthend,million, ...
- Mac安装protobuf 流程
下载 https://github.com/google/protobuf/releases 找到对应版本下载 编译 cd protobuf./autogen.sh./configuremake 安装 ...
- 第23章 I2C—读写EEPROM—零死角玩转STM32-F429系列
第23章 I2C—读写EEPROM 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.com/f ...
- ARC下需要注意的内存问题
之前发了一篇关于图片加载优化的文章,还是引起很多人关注的,不过也有好多人反馈看不太懂,这次谈谈iOS中ARC的一些使用注意事项,相信做iOS开发的不会对ARC陌生啦.这里不是谈ARC的使用,只是介绍下 ...
- HDU 1084 What Is Your Grade?(排序)
题目在这里:1084 题目描述: “Point, point, life of student!” This is a ballad(歌谣)well known in colleges, and yo ...