Uploadify Version 3.2
文档API地址:http://www.uploadify.com/documentation
Uploadify Version 3.2与之前的2.1版本参数已经很多不一样。
1Options选项设置
auto 选择文件后自动上传
buttonClass 给“浏览按钮”加css的class样式
buttonCursor 鼠标移上去形状:arrow箭头、hand手型(默认)
buttonImage 鼠标移上去变换图片
buttonText 按钮文字
checkExisting 在目录中检查文件是否已上传成功(1 ture,0 false)
debug 是否显示调试框(默认不显示false)
fileObjName 设置一个名字,在服务器处理程序中根据该名字来取上传文件的数据。默认为Filedata,如:‘fileObjName‘ : ‘fileupload‘, //和type=file的input的name属性一致
fileSizeLimit 设置允许上传文件最大值B, KB, MB, GB 比如:‘fileSizeLimit‘ : ‘20MB‘
fileTypeDesc 选择的文件的描述。这个字符串出现在浏览文件对话框中文件类型下拉框处。默认:All Files
fileTypeExts 允许上传的文件类型。格式:‘fileTypeExts‘ : ‘*.gif; *.jpg; *.png‘
formData 附带值,需要通过get or post传递的额外数据,如formData:{‘type‘ : ‘0‘, ‘islogin‘ : ‘${islogin}‘}。
height “浏览按钮”高度px
itemTemplate <itemTemplate>节点表示显示的内容。这些内容中也可以包含绑定到控件DataSource属性中元素集合的数据。
method 上传方式。默认:post
multi 选择文件时是否可以【选择多个】。默认:可以true
overrideEvents 不执行默认的onSelect事件
preventCaching 随机缓存值 默认true ,可选true和false.如果选true,那么在上传时会加入一个随机数来使每次的URL都不同,以防止缓存.但是可能与正常URL产生冲突
progressData 进度条上显示的进度:有百分比percentage和速度speed。默认百分比
queueID 给“进度条”加背景css的ID样式。文件选择后的容器ID
queueSizeLimit 允许多文件上传的数量。默认:999
removeCompleted 上传完成后队列是否自动消失。默认:true
removeTimeout 上传完成后队列多长时间后消失。默认 3秒 需要:‘removeCompleted‘ : true,时使用
requeueErrors 队列上传出错,是否继续回滚队列,即反复尝试上传。默认:false
successTimeout 上传超时时间。文件上传完成后,等待服务器返回信息的时间(秒).超过时间没有返回的话,插件认为返回了成功。 默认:30秒
swf swf文件的路径,本文件是插件自带的,不可用其它的代替.本参数不可省略
uploader 上传处理程序URL,本参数不可省略
uploadLimit 限制总上传文件数,默认是999。指同一时间,如果关闭浏览器后重新打开又可上传。
width “浏览按钮”宽度px
2Events 事件
onCancel 当取消一个上传队列中的文件时触发,删除时触发
onClearQueue 清除队列。当‘cancel‘方法带着*参数时,也就是说一次全部取消的时候触发.queueItemCount是被取消的文件个数(另外的按钮)
onDestroy 取消所有的上传队列(另外的按钮)
onDialogClose 当选择文件对话框关闭时触发,不论是点的‘确定‘还是‘取消‘都会触发.如果本事件被添加进了‘overrideEvents‘参数中,那么如果在选择文件时产生了错误,不会有错误提示框弹出
onDialogOpen 当选择文件框被打开时触发,没有传过来的参数
onDisable 关闭上传
onEnable 开启上传
onFallback 检测FLASH失败调用
onInit 每次初始化一个队列时触发
onQueueComplete 当队列中的所有文件上传完成时触发
‘onQueueComplete‘ : function(queueData) {
alert(queueData.uploadsSuccessful + ‘ files were successfully uploaded.‘);
}
queueData有两个属性:uploadsSuccessful成功上传文件的数量,uploadsErrored失败上传文件的数量。
onSelect 当文件从浏览框被添加到队列中时触发
onSelectError 选择文件出错时触发
onSWFReady flash准备好时触发
onUploadComplete当一个文件上传完成时触发
onUploadError 当文件上传完成但是返回错误时触发
onUploadProgress上传汇总
onUploadStart 一个文件上传之前触发
‘onUploadStart‘ : function(file) {
alert(‘Starting to upload ‘ + file.name);
}
fileObj:选择的文件对象,有name、size、creationDate、modificationDate、type 5个属性
onUploadSuccess 每个上传完成并成功的文件都会触发本事件,data就是后台返回的字符串,只能返回字符串才可以接收的到。
@RequestMapping(value = "/attachFile.do")
@ResponseBody
String uploadFile(HttpServletRequest request,HttpServletResponse response, BindException errors){
...
return file.getId();
}
‘onUploadSuccess‘: function (file, data, response) {
if (data != ‘‘) {
alert(data);
}
}
3Methods 方法
cancel 取消一个上传队列,参数为fileID是要上传文件的queueID,*表示队列中的所有文件。
destroy 取消所有上传队列。
jQuery(‘#fileupload‘).uploadify(‘destroy‘);
disable 禁止点击"浏览按钮"
$(‘#file_upload‘).uploadify(‘disable‘, true);
settings 返回或修改一个 uploadify实例的settings值。如:
$(‘#file_upload‘).uploadify(‘settings‘,‘buttonText‘,‘上传‘);
stop 停止当前的上传并重新添加到队列中去
$(‘#file_upload‘).uploadify(‘stop‘);
upload 上传指定的文件或者所有队列中的文件,参数为fileID是要上传文件的queueID,*表示队列中的所有文件。
jQuery(‘#fileupload‘).uploadify(‘upload‘,‘*‘);
4与spring结合上传的实例
上传文件的界面uploadFile.jsp:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@include file="/common/taglibs.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>上传文件</title>
<link href="${ctx }/js/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="${ctx }/js/uploadify/jquery.uploadify.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#fileupload").uploadify({
‘swf‘ : ‘${ctx}/js/uploadify/uploadify.swf‘,
‘uploader‘ : ‘${ctx}/upload.do‘,
‘formData‘ : {‘type‘ : ‘0‘, ‘islogin‘ : ‘${islogin}‘},
‘buttonText‘ : ‘选择文件‘,
‘width‘ : "80",
‘height‘ : "25",
‘queueID‘ : ‘fileQueue‘,
‘fileObjName‘ : ‘fileupload‘, //和以下input的name属性一致
‘auto‘ : false,
‘multi‘ : true,
‘queueSizeLimit‘ : 25,
‘fileSizeLimit‘ : ‘10MB‘,
‘fileTypeExts‘ :‘*.*‘,
‘fileTypeDesc‘ : ‘所有文件(*.*)‘,
‘onFallback‘:function(){
alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
}
});
});
/*
图片文件
‘fileExt‘ : ‘*.png;*.gif;*.jpg;*.bmp;*.jpeg‘,
‘fileDesc‘ : ‘图片文件(*.png;*.gif;*.jpg;*.bmp;*.jpeg)‘,
*/
</script>
</head>
<body>
<table style="width: 90%;">
<tr>
<td style="width: 100px;" align="center" valign="top">
<input id="fileupload" name="fileupload" type="file"/>
</td>
<td style="width: 100px;" align="center" valign="top">
<div id="file_upload-button" onclick="jQuery(‘#fileupload‘).uploadify(‘upload‘,‘*‘);" class="uploadify-button " style="height: 25px;cursor:pointer;line-height: 25px; width: 80px;">
<span class="uploadify-button-text">开始上传</span></div>
</td>
<td style="width: 100px;" align="center" valign="top">
<div id="file_upload-button" onclick="jQuery(‘#fileupload‘).uploadify(‘stop‘);" class="uploadify-button " style="height: 25px;cursor:pointer; line-height: 25px; width: 80px;">
<span class="uploadify-button-text">取消上传</span></div>
</td>
</tr>
<tr>
<td colspan="3" align="center"><div id="fileQueue"></div></td>
</tr>
</table>
</body>
</html>
后台处理方法:
@RequestMapping(value = "/upload.do")
public String uploadFile(HttpServletRequest request,HttpServletResponse response, BindException errors)
throws Exception {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
.getFile("fileupload");
String str = multipartRequest.getParameter("type");
if("0".equals(str)){
str="personal";
}else if("1".equals(str)){
str="department";
}else if("2".equals(str)){
str="organSystem";
}else{
str="";
}
// 获得文件名:
String realFileName = file.getOriginalFilename();
System.out.println("上传的文件名:" + realFileName);
// 获得根路径
File contxtPath=new File(request.getServletContext().getRealPath("/"));
// 创建文件存放路径
String ctxPath = contxtPath.getParent()+ "/userFiles/";
File dirPath = new File(ctxPath);
if (!dirPath.exists()) {
dirPath.mkdir();
}
ctxPath=ctxPath+str+"/";
dirPath = new File(ctxPath);
if (!dirPath.exists()) {
dirPath.mkdir();
}
String nowTimeStr = ""; //保存当前时间
String newFileName = ""; //保存新的文件名
SimpleDateFormat sDateFormat;
Random r = new Random();
int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; //获取随机数
sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); //时间格式化的格式
nowTimeStr = sDateFormat.format(new Date()); //当前时间
newFileName = nowTimeStr + rannum +"_"+realFileName;
File uploadFile = new File(ctxPath + newFileName);
FileCopyUtils.copy(file.getBytes(), uploadFile);
System.out.println("上传的文件路径:" + uploadFile.getPath());
return null;
}
spring-servlet.xml配置上传
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="40000000" />
<property name="maxInMemorySize" value="4096" />
</bean>
*********************
uploadify HTTP Error (302)错误
用uploadify就会报302错误。研究了半天,发现我上传的action中有根据session判断用户是否登录,如果没有登录就跳到登陆页,所以就出现了302跳转错误。原来更新了flash的版本以后,通过uploadify请求获取不到session的值。
************************
使用swfupload进行文件上传
首先下载swfupload,
需要导入的文件如下:
<script type="text/javascript" src="${ctx }/js/swfupload/swfupload.js"></script>
<script type="text/javascript" src="${ctx }/js/swfupload/handlers.js"></script>
<script type="text/javascript" src="${ctx }/js/swfupload/fileprogress.js"></script>
实例下面是一个使用swfupload进行上传的页面:
<%@page contentType="text/html; charset=utf-8" %>
<html>
<head>
<script src="${ctx}/js/jquery.js"></script>
<script type="text/javascript" src="${ctx }/js/swfupload/swfupload.js"></script>
<script type="text/javascript" src="${ctx }/js/swfupload/handlers.js"></script>
<script type="text/javascript" src="${ctx }/js/swfupload/fileprogress.js"></script>
<script type="text/javascript">
window.onload=function(){
//**************************上传新闻图片*****************************
var swfu_small = new SWFUpload({
// Backend Settings
upload_url: "${pageContext.request.contextPath}/SwfUpload?type=n",//完成上传的servlet
post_params: {"PHPSESSID": "${sessionid}"},
// File Upload Settings
file_size_limit : "5MB",
// 5MB
file_types : "*.jpg;*.gif;*.png",
file_types_description : "Image Files",
file_upload_limit : "0",
// Event Handler Settings - these functions as defined in Handlers.js
// The handlers are not part of SWFUpload but are part of my website and control how
// my website reacts to the SWFUpload events.
file_queue_error_handler : fileQueueError_small,
file_dialog_complete_handler : fileDialogComplete,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess_small,
upload_complete_handler : uploadComplete,
upload_start_handler : uploadStart_small,
// Button Settings
//button_image_url : "/images/XPButtonUploadText_61x22.png",
button_placeholder_id : "spanButtonPlaceholder_small",
button_width: 50,
button_height: 18,
button_text : ‘浏览‘,
button_text_style : ‘.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }‘,
button_text_top_padding: 0,
button_text_left_padding: 10,
button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
button_cursor: SWFUpload.CURSOR.HAND,
// Flash Settings
flash_url : "${pageContext.request.contextPath}/js/swfupload/swfupload.swf",
custom_settings : {
upload_target : "divFileProgressContainer_small"
},
// Debug Settings
debug: false
});
}
//开始上传文件调用的函数
function uploadStart_small(obj){
$("#upload_picture_msg_small").html("图片上传中,请稍等...");
}
//上传成功后调用的函数,data就是上传后图片的存放路径
function uploadSuccess_small(object,data,response){
$("#uploadPic_small").attr(‘src‘,‘${pageContext.request.contextPath}‘+data);
$("#uploadPic_small").show();
//将路径保存到text文本域,然后提交表单后将路径再保存到数据库中
$("#upload_picture_small").val(data);
$("#upload_picture_msg_small").html("");
$("#upload_picture_msg_small").attr("class","checked");
}
//上传出错后调用的函数
//code是出错代码
function fileQueueError_small(object,code,message){
var err = message;
if(code==‘-110‘){
err = "上传的图片大小超出范围";
}
$("#upload_picture_msg_small").html(err);
$("#upload_picture_msg_small").attr("class","error");
}
</script>
</head>
<body>
<div id="smallPicDiv">
<input type="text" id="upload_picture_small" name="imgNews" class="r_input_1 input" readonly>
<span id="smallPicUrlTip"></span>
<div style="display: inline; border: solid 1px #7FAAFF; background-color: #C5D9FF; padding: 2px;">
<span id="spanButtonPlaceholder_small"></span>
</div>
<span class=""><label id="upload_picture_msg_small"></label></span>
<div style="margin-top:5px">
<img src="" id="uploadPic_small" style="display:none">
</div>
</div>
</body>
</html>
上传文件的code是出错代码如下:
QUEUE_LIMIT_EXCEEDED : -100,
FILE_EXCEEDS_SIZE_LIMIT : -110,
ZERO_BYTE_FILE : -120,
INVALID_FILETYPE : -130
完成上传的servlet,路径如下:${pageContext.request.contextPath}/SwfUpload?type=n
public class SwfUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//判断是大图还是小图
String type = request.getParameter("type");
int pictureSize = 112;
if("s".equals(type)){
pictureSize = 45;
}
if("n".equals(type)){
pictureSize = 150;
}
String sessionid = request.getSession().getId();
//上传头像
String saveDirectory = this.getServletContext().getRealPath("/images/temp"); //上传文件存的路径
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
// 限制上传文件的大小为 5MB
int maxPostSize = 5 * 1024 * 1024;
MyFileRenamePolicy mfrp=new MyFileRenamePolicy();
try{
MultipartRequest multiRequest = new MultipartRequest(request , saveDirectory , maxPostSize, "utf-8",mfrp);
String picture = "";
File pictureFile =multiRequest.getFile("Filedata");
if(pictureFile != null){
picture = "/images/temp/"+pictureFile.getName();
ChangeImageSize.scale(pictureFile.getPath(), pictureFile.getPath(),pictureSize);
HttpSession session = request.getSession(true);
session.setAttribute(sessionid+"_img",picture);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(picture);
}else{
picture = multiRequest.getParameter("picture");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
************************
Ajax Upload文件上传插件允许你上传多个插件而无需刷新页面,可以使用任何的元素来显示文件选择窗口。它可以在所有主流的浏览器下工作,从2.0版本开始,不需要任何库运行。Ajax Upload文件上传插件不会污染任何命名空间,所以它与jQuery,Prototypejs,mootools其他JavaScript库兼容。
使用实例:
<prj:button id="btn_brower" value="上传" icon="icon-upload"/>
js代码:
导入的js文件:
<script type="text/javascript" src="${ctx}/js/common/ajax-upload.js"/>
$(function(){
new AjaxUpload($("#btn_brower"), {
action : "${ctx}/organ.do?upload&format=json",
name : "logo",
responseType : "json",
data : {
‘organInfoID‘ : $("#organInfoID").val(),‘type‘:"logos"
},
onSubmit : function(file, extension) {
if (extension != ‘jpg‘ && extension != ‘gif‘ && extension!=‘png‘) {
$.messager.alert(‘系统提示‘, "请选择jpg,gif,png格式的文件", ‘info‘);
return false;
}
return true;
},
onComplete : function(file, response) {
if (response.code==‘success‘ && response.logo) {
$("#logoImg").attr("src", "${ctx}/organ.do?showUpload&fpath="+response.logo);
$("#logo").val(response.logo);
}else{
$.messager.alert(‘系统提示‘, response.error, ‘info‘);
}
}
});
});
后台代码:
@RequestMapping(value = "/organ.do", params = "upload")
public void upload(HttpServletRequest request, HttpServletResponse response, String organID) {
PrintWriter out = getOut(response);
try {
MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
MultipartFile mfile = mrequest.getFile("logo");
String str=mrequest.getParameter("type");//指定存放文件的目录
File dirPath = null;
if (mfile != null) {
if("logos".equals(str)){
long maxsize=1024*1024*1024;//1M
long filesize=mfile.getSize();
if(filesize>maxsize){
out.print("{‘code‘:‘fail‘,‘error‘ : ‘上传图片大小不能找过1M!‘}");
return;
}
}
String logoFile = organDao.getLogoByInfoID(organID);
if (StringUtils.hasText(logoFile)) {
dirPath = new File(request.getServletContext().getRealPath(logoFile));
if (dirPath.exists()) {
dirPath = dirPath.getParentFile();
}
}
if (dirPath == null || !dirPath.exists()) {
File contextPath=new File(request.getServletContext().getRealPath("/"));
String ctxPath=contextPath.getParent()+"/uploadFiles/"+str+"/"+UUIDTools.getUUID();
dirPath=new File(ctxPath);
if(!dirPath.exists()){
dirPath.mkdirs();
}
}
String sourceName = dirPath.getAbsolutePath() + "/" + mfile.getOriginalFilename();
FileCopyUtils.copy(mfile.getBytes(), new File(sourceName));
String newPath = sourceName.replace(System.getProperty("file.separator"), "/");
out.print("{‘code‘:‘success‘,‘logo‘ : ‘" + newPath + "‘}");
return;
}
out.print("{‘code‘:‘fail‘,‘error‘ : ‘没有接收到上传图片!‘}");
}
catch (Exception ex) {
throw new CustomException(ex);
}
}
AjaxUpload方法的参数说明:
new AjaxUpload(‘#upload_button_id’, {
// 服务器端上传脚本
// 注意: 文件不允许上传到另外一个域上
action: ‘upload.php’,
// 文件上传的名字
name: ‘userfile’,
// 发送的附加数据
data: {
example_key1 : ‘example_value’,
example_key2 : ‘example_value2′
},
// 筛选后提交文件
autoSubmit: true,
// 您希望从服务器返回的数据类型
// HTML (text) 和 XML 自动检测
// 当您使用JSON作为响应时很实用,在这种情况下就设置为 “json”
// 也要设置服务器端的响应类型为text/html, 否则在IE6下是不工作的
responseType: false,
// 文件选择后使用
// 当autoSubmit为disabled时很管用
// 您可以通过返回false取消上传
// @参数file为上传文件的文件名
// @参数extension为那个文件(后缀名)
onChange: function(file, extension){},
// 文件上传时调用
// 您可以通过设置返回false 取消上传
// @参数file为上传文件的文件名
// @参数extension为那个文件(后缀名)
onSubmit: function(file, extension) {},
// 当文件上传完成的时候调用
// 警告!不要使用”false”字符串作为服务器的响应
// @参数file 指上传的文件名
// @参数 response 指服务器的响应
onComplete: function(file, response) {}
});
16文件上传
原文:http://blog.csdn.net/bin71722/article/details/51889721