jQuery File Upload example

jQuery File Upload is a file upload plugin for client side like php, jsp. here is a simple example(basic use) based on java.

1. the page:

飞信截图20150205114346

2. jsp

<%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%>
<%@ taglib uri=”http://java.sun.com/jstl/core_rt&#8221; prefix=”c”%>
<%@ taglib prefix=”s” uri=”/struts-tags” %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;
%>

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<base href=”<%=basePath%>”>

<title>应急预案维护</title>

<link href=”<c:url value=”/nnmis/view/ddrz_xhgz/easyui/demo.css”/>” rel=”stylesheet” type=”text/css” />
<link href=”<c:url value=”/nnmis/view/ddrz_xhgz/easyui/themes/default/easyui.css”/>” rel=”stylesheet” type=”text/css” />
<link rel=”stylesheet” href=”<c:url value=”/js/jQueryFileUpload/css/bootstrap.min.css”/>” type=”text/css”></link>
<link rel=”stylesheet” href=”<c:url value=”/js/jQueryFileUpload/css/jquery.fileupload.css”/>” type=”text/css”></link>
<link rel=”stylesheet” href=”<c:url value=”/js/jQueryFileUpload/css/jquery.fileupload-ui.css”/>” type=”text/css”></link>
<link href=”<c:url value=”/nnmis/view/ddrz_xhgz/easyui/themes/icon.css”/>” rel=”stylesheet” type=”text/css” />

<script type=”text/javascript” src=”<c:url value=”/js/jQueryFileUpload/jquery-1.9.1.min.js”/>”></script>
<script src=”<c:url value=”/nnmis/view/ddrz_xhgz/easyui/jquery.easyui.min.js”/>”></script>
<script type=”text/javascript” src=”<c:url value=”/js/jQueryFileUpload/js/vendor/jquery.ui.widget.js”/>”></script>
<script type=”text/javascript” src=”<c:url value=”/js/jQueryFileUpload/js/jquery.iframe-transport.js”/>”></script>
<script type=”text/javascript” src=”<c:url value=”/js/jQueryFileUpload/js/jquery.fileupload.js”/>”></script>
<script src=”<c:url value=”/tg/commons/easyui/locale/easyui-lang-zh_CN.js”/>”></script>

<script>

function searchList(){
var url = ‘<c:url value=”/nnmis/view/yjzh/SearchYjyaQuery.tg”/>’;

var begindate = $(‘#q_beginTime’).datetimebox(‘getValue’); //获取查询的起始日期
var enddate =$(‘#q_endTime’).datetimebox(‘getValue’); //获取查询的终止日期
var q_org = $(‘#q_org’).combobox(‘getValue’);
var q_title = $(‘#q_title’).val();

$(‘#dg’).datagrid(‘reload’,{ //重新载入datagrid
“qo[‘q_beginTime’]”:begindate,
“qo[‘q_endTime’]”:enddate,
“qo[‘q_org’]”:q_org,
“qo[‘q_title’]”:q_title
})
}

var actionUrl;
function addry(){
var strdate = new Date();
var stryear = strdate.getFullYear();
var strmonth = strdate.getMonth() + 1;
var strday = strdate.getDate();
var strhour = strdate.getHours();
var strminute = strdate.getMinutes();
var strsecond = strdate.getSeconds();
var upltime = stryear+’-‘+strmonth+’-‘+strday+’ ‘+strhour+’:’+strminute+’:’+strsecond;
//$(‘#fileupload’).form(‘clear’);//不能使用clear
$(‘#formdate’).datetimebox(‘setValue’,upltime);
$(‘#files’).empty();//清除已上传的文件列表
$(‘#progress .bar’).css(//还原进度条
‘width’,
0 + ‘%’
);
$(‘#dlg’).dialog(‘setTitle’, ‘新增预案’).dialog(‘open’);
actionUrl = ‘<c:url value=”/nnmis/view/yjzh/addYjyaQuery.tg”/>’;
$(‘#fileupload’).fileupload({//动态设置url,参数
url:actionUrl,
formData:{pubdate:$(‘#formdate’).datetimebox(‘getValue’)},
submit: function (e, data) {
var pubdate = $(‘#formdate’).datetimebox(‘getValue’);
if(pubdate == null || pubdate==”){
$.messager.alert(‘提示’,’发布时间不能为空!’,’error’);
return false;
}
}
});
}

function deletery(){
var row = $(‘#dg’).datagrid(‘getSelected’);
if(row){
$.messager.confirm(‘警告’,’您确认要删除吗?’,function(bt){
if(bt){
$.ajax({
url:'<c:url value=”/nnmis/view/yjzh/deleteYjyaQuery.tg?id=’ + row.id +'”/>’,
datatype: ‘json’,
success: function(data){
data = eval(‘(‘+data+’)’);
if(data.success){
var message=’删除成功!’;
if(data.message){
message=data.message;
}
$.messager.show({
title:’提示’,
msg:message,
showType:’slide’
});
$(‘#dg’).datagrid(‘reload’);
}else{
var message=’删除失败!’;
if(data.message){
message=data.message;
}
$.messager.alert(‘提示’,message,’error’);
}
}
});
}
});
}else{
$.messager.alert(‘提示’,’请选择要删除的人员!’,’error’);
}
}

$(function(){
$(‘#dg’).datagrid({onClickRow:function(index,data){
var row=$(‘#dg’).datagrid(‘getSelected’);
if(row){
var url = ‘<c:url value=”/nnmis/view/ddrz_xhgz/findByIDTC.tg”/>?id=’+row[“id”];
$(‘#vform’).form(‘load’,url);
}
}});

$(‘#fileupload’).fileupload({
dataType: ‘json’,
singleFileUploads:false,
done: function (e, data) {
if(data.result.error){
$.messager.alert(‘提示’,’上传失败!’,’error’);
}else{
$.each(data.result.files, function (index, file) {
$(‘<p/>’).text(file.name).appendTo(‘#files’);
});
$(‘#dg’).datagrid(‘reload’);
}
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$(‘#progress .bar’).css(
‘width’,
progress + ‘%’
);
}
});

$(‘#q_org’).combotree({
onLoadSuccess:function(){
$(‘#q_org’).combotree(‘tree’).tree(‘collapseAll’);
var root = $(‘#q_org’).combotree(‘tree’).tree(‘getRoot’);
$(‘#q_org’).combotree(‘tree’).tree(‘expand’,root.target);
}
});
});

</script>
</head>

<body>
<div id=”TC” class=”easyui-layout” style=” border: 2px; height: 100%; width:100%; background:#DCDCDC;”>
<div region=”center” style=”border:0px; height:100%;width:100%; “>
<form id=”query_form” method=”post”>
<table border=”0″ cellspacing=”4″ style=”height: 50px;”>
<tr><td align=”left” width=”60px”>发布部门: </td>
<td align=”left”>
<select id=”q_org” name=”ORGNUM” class=”easyui-combotree” style=”width:180px”
url=”<c:url value=’/nnmis/view/system/gainOrgNumWithDepTreeORGTREE.tg’/>”
checkbox=”false” cascadeCheck=”false” >
</select> </td>
<td align=”left” width=”60px”>预案名称:</td>
<td align=”left”><input id=”q_title” class=”easyui-validatebox” sytle=”width:130px”/></td>
<td align=”left” width=”60px”>发布时间: </td>
<td align=”left” width=”30px”>开始: </td>
<td align=”left”><input id=”q_beginTime” class=”easyui-datebox” style=”width:130px”> </td>
<td align=”left” width=”30px”>结束: </td>
<td align=”left”><input id=”q_endTime” class=”easyui-datebox” style=”width:130px”> </td>
<td align=”left”><a href=”javascript:void(0);” class=”easyui-linkbutton” iconCls=”icon-search” onclick=”searchList()”>查询</a> </td>
</tr>
</table>
</form>
<div style=”position:absolute;top:50px;bottom:0px;width:100%; “>
<div id=”tool”>
<a href=”javascript:void()” class=”easyui-linkbutton” iconCls=”icon-add” plain=”true” onclick=”addry()”>新增预案</a>
<a href=”javascript:void()” class=”easyui-linkbutton” iconCls=”icon-cancel” plain=”true” onclick=”deletery()”>删除</a>
</div>
<table id=”dg” singleSelect=”true” style=”width:100%,height:100%” rownumbers=”true” border=”true” pagination=”true” pageSize=”100″
fit=”true” toolbar=”#tool” url=”<c:url value=’/nnmis/view/yjzh/SearchYjyaQuery.tg’/>”>
<thead>
<tr>
<th field=”id” width=”80″ hidden=”true”></th>
<th field=”filename” width=”410″ sortable=”true”>预案名称</th>
<th field=”orgname” width=”130″ sortable=”true”>发布部门</th>
<th field=”uploadtime” width=”130″ sortable=”true”>发布时间</th>
<th field=”personname” width=”110″ sortable=”true”>发布人</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<div id=”dlg” style=”width: 400px; height: 250px;” class=”easyui-dialog” closed=”true” modal=”true” buttons=”#dlg-buttons”>
<div style=”padding-left: 10px; padding-top: 10px;”>
<div style=”float: center”>
<form id=”fileupload” method=”post” style=”margin: 0; padding: 0″ enctype=”multipart/form-data”>
<table>
<tr>
<td style=”width: 60px”>发布时间</td>
<td>
<input id=”formdate” name=”model.pubdate” class=”easyui-datetimebox” style=”width:180px”></input>
</td>
</tr>
<tr>
<td valign=”top” style=”width: 60px”>选择文件</td>
<td>
<span class=”btn btn-success fileinput-button”>
<i class=”glyphicon glyphicon-plus”></i>
<span>选择文件</span>
<input type=”file” id=”formfile” name=”files” multiple></input>
</span>
<div id=”progress” class=”progress”>
<div class=”bar” style=”width: 0%;”></div>
</div>
</td>
</tr>
<tr>
<td valign=”top”>已上传:</td>
<td><div id=”files” class=”files”></div>
</td>
</tr>
</table>
</form>
</div>
<div style=”clear: both”></div>
</div>
<div id=”dlg-buttons” style=”text-align: center;”>

<a href=”javascript:void()” class=”easyui-linkbutton” iconCls=”icon-cancel” onclick=”javascript:$(‘#dlg’).dialog(‘close’)”>关闭</a>
</div>
</div>
</body>
</html>

another way to send formdata:

$(‘#fileupload’).fileupload({//动态设置url,参数
url:actionUrl
});
$(‘#fileupload’).bind(‘fileuploadsubmit’,function(e,data) {
data.formdata = {
pubdate:$(‘#formdate’).datetimebox(‘getValue’),
equtype:$(‘#formtype’).combobox(‘getValue’)
};
if(data.formdata.equtype == null || !data.formdata.equtype){
$.messager.alert(‘提示’,’设备类型不能为空!’,’error’);
return false;
}
});

3. server side

public void test(){
try {
System.out.println(“test….”);
System.out.println(request.getParameter(“stapara”));
System.out.println(pubdate);
String serverDir = ServletActionContext.getServletContext().getRealPath(“/”);
if (!”\\”.equals(serverDir.substring(serverDir.length() – 1))) {
serverDir = serverDir + “\\”;
}
JsonArray jArray = new JsonArray();
if (files != null) {
String origin = “”;
String format = “”;
String savename = “”;
String savePath = “”;
File ofile = null;
for (int i = 0; i < files.size(); i++) {
JsonObject jObject = new JsonObject();
jObject.addProperty(“name”, filesFileName.get(i));
// jObject.addProperty(“size”, 1);
// jObject.addProperty(“url”, “http://google.com&#8221;);
// jObject.addProperty(“thumbnail_url”, “http://google.com&#8221;);
// jObject.addProperty(“delete_url”, “http://google.com&#8221;);
// jObject.addProperty(“delete_type”, “GET”);
jArray.add(jObject);
System.out.println(filesFileName.get(i));
// ofile = files.get(i);
// origin = filesFileName.get(i);
// format = origin.substring(origin.lastIndexOf(“.”));
// File waitSaveFile = new File(serverDir + “cloudFiles\\”
// + “\\” + origin);
// if (waitSaveFile.exists()) {
// int index = 0;
// String temporigin = origin.substring(0,
// origin.lastIndexOf(“.”));
// do {
// index = index + 1;
// waitSaveFile = new File(serverDir + “cloudFiles\\” + “\\” + temporigin + “(”
// + index + “)” + format);
// } while (waitSaveFile.exists());
// savename = temporigin + “(” + index + “)” + format;
// } else {
// savename = origin;
// }
// waitSaveFile = null;
// savePath = serverDir + “cloudFiles\\” + “\\”
// + savename;
// File saveFile = new File(savePath);
// FileUtils.copyFile(ofile, saveFile);//upload and save
}
}
outJsonPlainString(response, “{\”error\”:false,\”files\”:” + jArray.toString() + “}”);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();

outJsonPlainString(response, “{\”error\”:true}”);
}
}

parameter value in formdata:

at server side, parameter is just as client side. if in html used as <input name=’model.pubdate’ />, the pubdate can get at model.getPubdate(). if in html <input name=’pubdate’ />, then use private String pubdate directly.

//reference:

https://github.com/blueimp/jQuery-File-Upload/

http://avnpc.com/pages/single-file-upload-component-by-jquery-file-upload

http://blog.csdn.net/sq111433/article/details/16872403

http://blog.csdn.net/sunpeiyumail/article/details/7665668

This entry was posted in Computer, Java, javascript. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s