easyui +plupload批量上傳檔案,easyuiplupload
1.js+jsp
//上傳附件
function makerUpload(aloneType,id){
UploaderAloneType(aloneType,id,function(files){ //執行上傳
findAttachment(); //回顯
});
}
//執行上傳
function UploaderAloneType(aloneType,id,callBack){
var addWin = $('<div />');
var upladoer = $('<iframe/>');
upladoer.attr({'src':'${ctx}/attachment/goToUploader?aloneType='+aloneType+'&id='+id,width:'100%',height:'100%',frameborder:'0',scrolling:'no'});
addWin.window({
title:"上傳檔案",
height:350,
width:550,
minimizable:false,
modal:true,
collapsible:false,
maximizable:false,
resizable:false,
content:upladoer,
onClose:function(){
var fw = GetFrameWindow(upladoer[0]);
var files = fw.files;
$(this).window('destroy');
callBack.call(this,files);
},
onOpen:function(){
var target = $(this);
setTimeout(function(){
var fw = GetFrameWindow(upladoer[0]);
fw.target = target;
},100);
}
});
}
//執行回顯
function findAttachment(){
//查詢附件類型
$.get("${ctx}/dictionary/combox?code=lfiletype",{},function(typeData){
typeData = $.parseJSON(typeData);
var loanid = $("#loanid").val();
var url = "${pageContext.request.contextPath}/toDoList/attrDatagrid?ciid=${lcf.loan.ciid}&zipai=${lcf.loan.zipai}&loanid=${lcf.loan.loanid}";
$.get(url,function(result){
debugger;
var rows = $.parseJSON(result).rows;
$("#imgurls").html("");
for(var j=0;j<typeData.length;j++){
var parentp = $("#imgurls").append("<p class='ptitle' style='margin-bottom: 10px;'><span>"+typeData[j].text+"</span></p>");
if(null!=rows){
for(var i=0;i<rows.length;i++){
if(rows[i].ftypeid == typeData[j].code) {
parentp.append('<li onclick="selectImg('+i+')"><img id="selectImg'+i+'" src="'+rows[i].fileurl+'"/></li>');
}
}
}
}
selectImg(0);
});
});
//jsp
<a class="easyui-linkbutton" href="javascript:makerUpload('shenHe',${loanid})">上傳附件</a><br/>
//檔案上傳介面
<%-----------------------------------------------------------
* 檔案名稱: upload.jsp
* 版本:
* 描述: 個貸 、理財公用頁面
* 著作權:
* ////////////////////////////////////////////////////////
* 建立者:
* 建立日期: 2014/7/14
* 修改者:
* 修改日期:
* 修改說明:
-----------------------------------------------------------%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>檔案上傳</title>
<link rel="stylesheet" href="${ctx}/jslib/plupload/queue/css/jquery.plupload.queue.css" type="text/css"></link>
<script type="text/javascript" src="${ctx}/jslib/plupload/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="${ctx}/jslib/plupload/plupload.js"></script>
<script type="text/javascript" src="${ctx}/jslib/plupload/plupload.html4.js"></script>
<script type="text/javascript" src="${ctx}/jslib/plupload/plupload.html5.js"></script>
<script type="text/javascript" src="${ctx}/jslib/plupload/plupload.flash.js"></script>
<script type="text/javascript" src="${ctx}/jslib/plupload/zh_CN.js"></script>
<script type="text/javascript" src="${ctx}/jslib/plupload/queue/jquery.plupload.queue.js"></script>
<body >
<div id="uploader"> </div>
<script type="text/javascript">
var files = [];
var errors = [];
var type = 'file';
//var chunk = eval('${param.chunk}');
var chunk = false;
var max_file_size = '5mb';
var filters = {title : "檔案", extensions : "jpg,jpeg,gif,png"};
$("#uploader").pluploadQueue($.extend({
runtimes : 'flash,html4,html5',
url : '${ctx}/attachment/upload?id=${id}&lfiletype=${lfiletype}&userId=${sessionScope.currentUser.id}&f=${f}&aloneType=${aloneType}',
max_file_size : max_file_size,
file_data_name:'file',
unique_names:true,
filters : [filters],
flash_swf_url : '${ctx}/jslib/plupload/plupload.flash.swf',
init:{
FileUploaded:function(uploader,file,response){
if(response.response){
var rs = $.parseJSON(response.response);
if(rs.status){
files.push(file.name);
}else{
errors.push(file.name);
}
}
},
UploadComplete:function(uploader,fs){
var e= errors.length ? ",失敗"+errors.length+"個("+errors.join("、")+")。" : "。";
alert("上傳完成!共"+fs.length+"個。成功"+files.length+e);
target.window("close");
}
}
},(chunk ? {chunk_size:'1mb'} : {})));
</script>
</body>
</html>
2.後台代碼
/**
*
* goTouploader 前往附件上傳介面
* @author zyh
* @date 2014-8-6 下午3:24:13
* @param chunk
* @param id 業務主鍵
* @param lfiletype 附件類型
* @return
*/
@RequestMapping("/goToUploader")
public String goToUploader(String chunk,String id,String lfiletype,String f,String aloneType,HttpServletRequest requst){
requst.setAttribute("id", id);
requst.setAttribute("lfiletype", lfiletype);
requst.setAttribute("chunk", chunk);
requst.setAttribute("f", f);
requst.setAttribute("aloneType",aloneType);
return "/loan/upload";
}
/**
* 上傳附件
* upload
* @author robo
* @date 2014-7-10 上午11:31:11
* @param id
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public void uploadFile(String id,String lfiletype,int userId,String f,String aloneType,HttpServletRequest request,HttpServletResponse response)throws IOException {
Json j = new Json();
if (ServletFileUpload.isMultipartContent(request)) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024);
String webRootPath = request.getSession().getServletContext().getRealPath("/");
String tmp = "/tmp";
File tempFile = new File(webRootPath+tmp);
//不存在時建立目錄 add by majie 2015-11-30 19:28:05
if(!tempFile.exists()){
tempFile.mkdirs();
}
factory.setRepository(tempFile);//設定臨時目錄
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setSizeMax(5 * 1024 * 1024);//設定附件大小
//圖片訪問url
// 開始讀取上傳資訊
List<FileItem> fileItems = upload.parseRequest(request);
// 依次處理每個上傳的檔案
List<Attachments> list = new ArrayList<Attachments>() ;
//遍曆檔案
for(FileItem item:fileItems) {
// 忽略其他不是檔案域的所有表單資訊
if (!item.isFormField()) {
String fname = item.getName();
String filetype = "";
if(StringUtils.isNotBlank(fname)){
int postion = fname.lastIndexOf(".");
if (postion != -1) {
filetype = fname.substring(postion + 1, fname.length()); //副檔名
}
}
filetype=filetype.toLowerCase();
InputStream fis = item.getInputStream();
if(fis== null)
continue;
String remoteFilename = System.currentTimeMillis()+""+Math.round(Math.random()*1000)+"."+filetype;
Attachments att = new Attachments() ;
att.setCreator(Long.valueOf(userId));
att.setMainType(1);
att.setFilename(fname);
att.setFiletype(filetype);
att.setAloneType(aloneType);
att.setFileurl(request.getContextPath()+"/file/"+remoteFilename);
File distFile = new File(webRootPath+"/file");
if(!distFile.exists())
distFile.mkdirs();
distFile = new File(distFile.getAbsolutePath()+"/"+remoteFilename);
distFile.createNewFile();
FileOutputStream fos = new FileOutputStream(distFile);
byte[] b = new byte[1024];
while((fis.read(b)) != -1){
fos.write(b);
}
fis.close();
fos.close();
//業務主鍵[信貸、理財]
if(StringUtils.isNotBlank(id)){
att.setMainid(Long.parseLong(id));
}
if(StringUtils.isNotBlank(lfiletype)){
att.setFtypeid(Long.parseLong(lfiletype));
}
list.add(att);
response.getWriter().write("{\"status\":true,\"newName\":\""+fname+"\"}");
}
}
loanService.uploadFile(list, userId);
j.setSuccess(true);
j.setMsg("上傳成功");
} catch (BusinessException e) {
e.printStackTrace();
j.setSuccess(false);
j.setMsg("上傳失敗");
}catch (Exception e) {
e.printStackTrace();
j.setSuccess(false);
j.setMsg("上傳失敗");
}finally{
}
}
// ResponseUtil.responseText(response, JSON.toJSONString(j));
}
/**
* 附件列表
* attrDatagrid
* @author robo
* @date 2014-8-5 上午10:09:38
* @param loanid
* @return
*/
@RequestMapping("/attrDatagrid")
@ResponseBody
public Grid attrDatagrid(long ciid,String zipai,HttpServletRequest request,long loanid){
Grid grid = new Grid();
List<Attachments> list = new ArrayList<Attachments>();
String project = request.getContextPath()+File.separator+"app"+File.separator;
String idCard = loanServiceOne.getIdCardByCiid(ciid);
if(idCard != null){
//查詢註冊使用者資訊
LoanUser loanUser = loanCustomerService.getLoanUserByIdCard(idCard);
if(loanUser.getCard_zhengmian_src() != null){
list.add(new Attachments(2L,project+loanUser.getCard_zhengmian_src()));
}
if(loanUser.getCard_fanmian_src() != null){
list.add(new Attachments(2L,project+loanUser.getCard_fanmian_src()));
}
if(loanUser.getCard_zipai_src() != null){
list.add(new Attachments(2L,project+loanUser.getCard_zipai_src()));
}
}
List<Attachments> findAttachmentsList;
try {
findAttachmentsList = loanService.findAttachmentsList(loanid);
if(findAttachmentsList!=null&&findAttachmentsList.size()>0){
for (Attachments attachments : findAttachmentsList) {
list.add(new Attachments(1L, attachments.getFileurl()));
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (BusinessException e) {
e.printStackTrace();
}
if(zipai != null && zipai.length()>0){
list.add(new Attachments(1L,project+zipai));
}
grid.setRows(list);
return grid;
}