<%@page import="com.mango.core.Constant"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %><%@ taglib uri="/auth" prefix="oa"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
if(pageContext.getAttribute("path") == null){
pageContext.setAttribute("path", path);
}
%>
<link rel="shortcut icon" href="${path }/images/favicon.ico" type="image/x-icon" />
<title>雲實驗室</title>
<link href="${path}/css/style.css" rel="stylesheet" type="text/css"></link>
<link href="${path}/css/style_wrong.css" rel="stylesheet" type="text/css"></link>
<script type="text/javascript" src="${path}/js/jquery.min.js"></script>
<link rel="stylesheet" href="${path}/js/artdialog/css/ui-dialog.css" />
<script type="text/javascript" src="${path}/js/artdialog/dist/dialog-min.js"></script>
<script type="text/javascript">
var contextPath = "${path}";//爲了適應引用js文件的路徑
</script>
<body>
<span id="container" ><input type="button" value="上傳附件" id="pickfiles"></span>
<div id="hiddenTR"></div >
<table id="filelist" style="width: 100%;">
</table>
</body>
---------file.add.js
var uploader;
$(document).ready(function(){
initFileUpload();
});
function initFileUpload(){
var index = 0;//
uploader = new plupload.Uploader({
runtimes : 'html5,flash,silverlight,html4',
browse_button : 'pickfiles',
container: document.getElementById('container'),
max_file_size: '50mb', // 文件上傳最大限制。
chunk_size: '1mb', // 上傳分塊每塊的大小,這個值小於服務器最大上傳限制的值即可。
unique_names: true, // 上傳的文件名是否唯一
url : contextPath+'/attachment/fileUpload.jhtml',//上傳到後臺
flash_swf_url : contextPath+'/js/upload/Moxie.swf',
silverlight_xap_url : contextPath+'/upload/js/Moxie.xap',
filters : {
prevent_duplicates : true //不允許選取重複文件
}
});
//在實例對象上調用init()方法進行初始化
uploader.init(function(){
//document.getElementById('filelist').innerHTML = '';
});
//錯誤處理
uploader.bind('Error', function (uploader, args) {
//發生錯誤
if (args.code == plupload.FILE_DUPLICATE_ERROR) {
showalert( args.file.name + '已在上傳隊列中!');
// showWindow("uploadError",650,200);
} else if (args.code == plupload.IMAGE_FORMAT_ERROR) {
showalert( args.file.name + '的圖片格式暫不支持上傳!');
} else if (args.code == plupload.IMAGE_DIMENSIONS_ERROR) {
showalert( args.file.name + '上傳隊列中文件超出50MB!');
} else if (args.code == plupload.FILE_EXTENSION_ERROR) {
showalert( args.file.name + '的文件格式暫不支持上傳!');
} else if (args.code == plupload.FILE_SIZE_ERROR) {
showalert( args.file.name + '的文件大小超出50MB!');
} else if (args.code == plupload.IO_ERROR) {
showalert( args.file.name + '讀取失敗,請檢查該文件是否存在,或被其他程序佔用!');
}
});
// 添加文件
uploader.bind('FilesAdded',function(uploader,files){//後臺上傳到服務器後,將files拼成json返回到前臺頁面
plupload.each(files, function(file) {
$("#filelist").append("<tr id="+file.id+" >"+
"<td class=\"fileName\" ><span>"+file.name +"</span>(" + plupload.formatSize(file.size) + ")<span></span></td>"+
"<td class=\"fileTime\" >"+new Date().format("yyyy-MM-dd hh:mm")+"</td>"+
"<td class=\"fileOper\"><a href=\"javascript:removeFile('"+file.id+"')\" class=\"alinkmodify\">移除</a></td>"+
"</tr>");
});
uploader.start();
});
//上傳進度
uploader.bind('UploadProgress',function(uploader,file){
//我們可以利用這些參數提供的信息來做比如更新UI,提示上傳進度等操作
document.getElementById(file.id).getElementsByTagName('span')[1].innerHTML = '' + file.percent + "%";
});
// 開始上傳
// $("#uploadfiles").click(function(){
// uploader.start();
// });
// 上傳完成之後
uploader.bind('FileUploaded',function(uploader,file,responseObject){
if(responseObject.status==200){
var result = eval('('+responseObject.response+')');
// 圖片名稱 和地址 放置在隱藏域中
$("#hiddenTR").append("<input type=\"hidden\" name=\"fileName\" id=\"fileName"+index+"\" value=\""+file.name+"\"/>"+
"<input type=\"hidden\" name=\"filePath\" id=\"filePath"+index+"\" value=\""+result.filePath+"\"/>");
//$("#fileName" + index).val(file.name);
//$("#filePath" + index).val(result.filePath);
index = index +1;
if($("#upFile") != undefined){
$("#upFile").show();
}
}else{
alert(result);
}
});
}
/**
* 刪除文件
*/
function removeFile(fileId){
$("tr[id='" + fileId + "']").remove();// 刪除當前行
}
--------file.edit.js
var uploader;
$(document).ready(function(){
var index = 0;//
uploader = new plupload.Uploader({
runtimes : 'html5,flash,silverlight,html4',
max_file_size: '50mb', // 文件上傳最大限制。
browse_button : 'pickfiles',
container: document.getElementById('container'),
url : contextPath+'/attachment/fileUpload.jhtml',
flash_swf_url : contextPath+'/js/upload/Moxie.swf',
silverlight_xap_url: contextPath+'/upload/js/Moxie.xap',
filters : {
// mime_types : [ //只允許上傳圖片和zip文件
// { title : "圖片格式", extensions : "jpg,gif,png,jpeg" },
// { title : "壓縮包格式", extensions : "zip,rar" },
// { title : "OFFICE格式", extensions : "doc,docx,ppt,pptx,xls,xlsx,rtf,txt" }
// ],
prevent_duplicates : true //不允許選取重複文件
}
});
//在實例對象上調用init()方法進行初始化
uploader.init(function(){
//document.getElementById('filelist').innerHTML = '';
});
//錯誤處理
uploader.bind('Error', function (uploader, args) {
//發生錯誤
if (args.code == plupload.FILE_DUPLICATE_ERROR) {
showalert('文件錯誤:' + args.file.name + '已在上傳隊列中!');
// showWindow("uploadError",650,200);
} else if (args.code == plupload.IMAGE_FORMAT_ERROR) {
showalert('文件錯誤:' + args.file.name + '的圖片格式暫不支持上傳!');
} else if (args.code == plupload.IMAGE_DIMENSIONS_ERROR) {
showalert('文件錯誤:' + args.file.name + '上傳隊列中文件超出50MB!');
} else if (args.code == plupload.FILE_EXTENSION_ERROR) {
showalert('文件錯誤:' + args.file.name + '的文件格式暫不支持上傳!');
} else if (args.code == plupload.FILE_SIZE_ERROR) {
showalert('文件錯誤:' + args.file.name + '的文件大小超出50MB!');
} else if (args.code == plupload.IO_ERROR) {
showalert('文件錯誤:' + args.file.name + '讀取失敗,請檢查該文件是否存在,或被其他程序佔用!');
}
});
// 添加文件
uploader.bind('FilesAdded',function(uploader,files){
plupload.each(files, function(file){
$("#filelist").append("<tr id="+file.id+" height=\"30px\">"+
"<td class=\"fileName\" >"+file.name +"(" + plupload.formatSize(file.size) + ")<span></span></td>"+
"<td class=\"fileTime\" >"+new Date().format("yyyy-MM-dd hh:mm")+"</td>"+
"<td class=\"fileOper\"><a href=\"javascript:removeFile('"+file.id+"')\" class=\"alinkmodify\">移除</a></td>"+
"</tr>");
});
uploader.start();
});
//上傳進度
uploader.bind('UploadProgress',function(uploader,file){
//我們可以利用這些參數提供的信息來做比如更新UI,提示上傳進度等操作
document.getElementById(file.id).getElementsByTagName('span')[0].innerHTML = '' + file.percent + "%";
});
// 開始上傳
// $("#uploadfiles").click(function(){
// uploader.start();
// });
//取消上傳
// $("#uploadfiles").click(function(){
// uploader.stop();
// });
//
uploader.bind('FileUploaded',function(uploader,file,responseObject){
if(responseObject.status==200){
var result = eval('('+responseObject.response+')');
// 圖片名稱 和地址 放置在隱藏域中
$("#hiddenTR").append("<input type=\"hidden\" name=\"fileName\" id=\"fileName"+index+"\" value=\""+file.name+"\"/>"+
"<input type=\"hidden\" name=\"filePath\" id=\"filePath"+index+"\" value=\""+result.filePath+"\"/>"+
"<input type=\"hidden\" name=\"thumbpath\" id=\"thumbpath"+index+"\" value=\""+result.thumbpath+"\"/>");
//$("#fileName" + index).val(file.name);
//$("#filePath" + index).val(result.filePath);
index = index +1;
if($("#upFile") != undefined){
$("#upFile").show();
}
}
});
});
/**
* 刪除文件 根據主鍵 非物裏刪除
*/
function deleteFile(fileId){
var d = dialog({
title: '提示',
width:'200',
content: '確定移除該附件?',
okValue: '確定',
ok: function () {
$("tr[id='" + fileId + "']").remove();// 刪除當前行
$.ajax({
type:'POST',
url:contextPath+'/attachment/delete.jhtml',
cache:false,
data:'attachmentId='+fileId,
success:function (data){
uploader.removeFile(fileId);
}
});
if($("#upFile") != undefined){
$("#upFile").show();
}
},
cancelValue: '取消',
cancel: function () {
return ;}
});
d.showModal();
}
/**
* 刪除文件
*/
function removeFile(fileId){
$("tr[id='" + fileId + "']").remove();// 刪除當前行
}
----重寫 new Date()格式化方法 commom.js
function showDiv() {
document.getElementById('popWindow').style.display = 'block';
document.getElementById('maskLayer').style.display = 'block';
}
function closeDiv() {
document.getElementById('popWindow').style.display = 'none';
document.getElementById('maskLayer').style.display = 'none';
}
//瀏覽器窗口垂直居中
function popup(popupName){
var _scrollHeight = $(document).scrollTop(),//獲取當前窗口距離頁面頂部高度
_windowHeight = $(window).height(),//獲取當前窗口高度
_windowWidth = $(window).width(),//獲取當前窗口寬度
_popupHeight = popupName.height(),//獲取彈出層高度
_popupWeight = popupName.width();//獲取彈出層寬度
_posiTop = (_windowHeight - _popupHeight)/2 + _scrollHeight;
_posiLeft = (_windowWidth - _popupWeight)/2;
popupName.css({"left": _posiLeft + "px","top":_posiTop + "px"});//設置position
}
/**
* 需要定義兩塊區域
* 1.id=projectIds的顯示區域 2.id=id_name_array隱藏div 用於表單提交
* @rand 隨機參數,建議每個頁面rand不同
* @return
*/
function projectSelectArtDialog(rand){
var selectedId=$("#selectedId").val();
var top=dialog({
id: 'projectSelect'+rand,
width: 750,
title: '選擇關聯項目',
url: contextPath+'/article/getProjectCommom.jhtml?selectProject='+selectedId,
onclose: function () {
//console.log('onclose');
}
});
top.showModal();
}
//參與成員,獲取內容
/**
* 需要定義兩塊區域
* 1.id=person的顯示區域 2.id=selectedId隱藏表單,用於表單提交
* @rand 隨機參數,建議每個頁面rand不同
* @return
*/
function personSelect(rand){
var selectedId=$("#selectedId").val();
var top=dialog({
id: 'userSelect'+rand,
width: 750,
title: '選擇項目負責人',
url: contextPath+'/user/getProjectTeamUserCommon.jhtml?selectUser='+selectedId,
onclose: function () {
//console.log('onclose');
}
});
top.showModal();
}
/**
* 後退一步
* */
function go_back(){
window.history.back();
}
/**
* 跳轉頁面
* @param url
* @return
*/
function to(url){
location.href=contextPath+"/"+url;
}
/**
* alert提示
* @param msg
* @return
*/
function showalert(msg){
var d = dialog({title: '提示',width:'200',height:'50', content: '<span style="text-align: center;width:100%;">'+msg+'</sapn>'});
d.showModal();
}
/**
* alert提示(time毫秒後自動關閉)
* @param msg
* @return
*/
function showalertTime(msg,time){
var d = dialog({title: '提示',width:'200',height:'50', content: '<span style="text-align: center;width:100%;">'+msg+'</sapn>'});
d.showModal();
setTimeout(function(){
d.close();
}, time)
}
/**
* dialog 例子 彈出新url
* @param url
* @return
*/
function showUrl(url){
var top=dialog({
id: 'test-dialog',
title: 'loading..',
url: url,
//quickClose: true,
onshow: function () {
//console.log('onshow');
},
oniframeload: function () {
//console.log('oniframeload');
},
onclose: function () {
if (this.returnValue) {
$('#value').html(this.returnValue);
}
//console.log('onclose');
},
onremove: function () {
//console.log('onremove');
}
});
top.showModal();
//子頁面可以通過top.$("#wenben").val("ssssss2222s") 向父頁面傳遞值
}
/**
* 強制保留4位小數,
* @param x
* @return
*/
function toDecimal2(x) {
var f = parseFloat(x);
if (isNaN(f)) {
return false;
}
var f = Math.round(x*10000)/10000;
var s = f.toString();
return s;
}
(function($){
$.fn.serializeJson=function(){
var serializeObj={};
$(this.serializeArray()).each(function(){
serializeObj[this.name]=this.value;
});
return serializeObj;
};
})(jQuery);
//判斷空
function isNull(str) {
str = $.trim(str);
if (str == null||str == "" ) {
return true;
}
return false;
}
Date.prototype.format =function(format)
{
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
}
if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
(this.getFullYear()+"").substr(4- RegExp.$1.length));
for(var k in o)if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length==1? o[k] :
("00"+ o[k]).substr((""+ o[k]).length));
return format;
}
//數字處理公共函數
/*
* 小數四捨五入
* number:需要處理的參數
* fractionDigits:保留幾位小數
*/
function round2(number, fractionDigits) {
// if(number == 0 || number == 0.0 || number == 0.00){
// return "0.00";
// }
with (Math) {
var num = round(number * pow(10, fractionDigits))
/ pow(10.00, fractionDigits);
if(num.toString().indexOf(".") <= 0){
return num.toString() + ".00";
}else{
return num;
}
}
}
/**
* 元轉萬元 保留兩位小數
*
* @param number
* @return
*/
function wanyuan(number) {
if(number != undefined &&(number == 0 || number == 0.0 || (number.toString().indexOf("0.00") == 0))){
return "0";
}
with (Math) {
var val= number/ pow(10, 4);
return val.toFixed(2);
}
}
/**
* form 轉json
* $("#shouhuoForm").serializeObject();
*/
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
function escapeJquery(srcString)
{
// 轉義之後的結果
var escapseResult = srcString;
// javascript正則表達式中的特殊字符
var jsSpecialChars = ["\\", "^", "$", "*", "?", ".", "+", "(", ")", "[",
"]", "|", "{", "}"];
// jquery中的特殊字符,不是正則表達式中的特殊字符
var jquerySpecialChars = ["~", "`", "@", "#", "%", "&", "=", "'", "\"",
":", ";", "<", ">", ",", "/"];
for (var i = 0; i < jsSpecialChars.length; i++) {
escapseResult = escapseResult.replace(new RegExp("\\"
+ jsSpecialChars[i], "g"), "\\"
+ jsSpecialChars[i]);
}
for (var i = 0; i < jquerySpecialChars.length; i++) {
escapseResult = escapseResult.replace(new RegExp(jquerySpecialChars[i],
"g"), "\\" + jquerySpecialChars[i]);
}
return escapseResult;
}
//右側懸浮
$(document).ready(function(){
$(".side ul li").hover(function(){
$(this).find(".sidebox").stop().animate({"width":"124px"},200).css({"opacity":"1","filter":"Alpha(opacity=100)","background":"#7BBAEF"})
},function(){
$(this).find(".sidebox").stop().animate({"width":"54px"},200).css({"opacity":"0.8","filter":"Alpha(opacity=80)","background":"#7BBAEF"})
});
});
//回到頂部
function goTop(){
$('html,body').animate({'scrollTop':0},600);
}
--------後臺代碼
package com.frame.action.attachment;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.alibaba.fastjson.JSONObject;
import com.common.util.DateUtils;
import com.common.util.IdGenerator;
import com.common.util.ZipUtils;
import com.frame.service.attachment.AttachmentService;
import com.frame.vo.attachment.AttachmentVo;
import com.frame.vo.user.UserVo;
import com.mango.controller.BaseController;
import com.mango.core.Constant;
import com.mango.core.Page;
/**
*
* @author zhangzd
*/
@Controller
@RequestMapping("/attachment")
public class AttachmentAction extends BaseController{
@Resource
private AttachmentService attachmentService;
/**
* 列表頁面
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/list.jhtml")
public String list(HttpServletRequest request,HttpServletResponse response,
@ModelAttribute("form") AttachmentVo attachmentVo) throws Exception{
logger.info("查詢列表");
//獲取分頁標籤數據
Page page = new Page(request.getParameter("pStart"), "10", request.getParameter("total"));
// 調service方法
request.setAttribute("attachmentList", attachmentService.getAttachmentForPage(attachmentVo,page ));
//放到request中,回顯
request.setAttribute("attachmentVo", attachmentVo);
request.setAttribute("page", page);
//springmvc 已經配置路徑和後綴名。對應jsp/orderList.jsp
return "user/attachmentList";
}
/**
* 跳轉到添加頁面
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/delete.jhtml")
public String delete(HttpServletRequest request,
HttpServletResponse response) throws Exception{
JSONObject json = new JSONObject();
int bool =0;
String attachmentId = request.getParameter("attachmentId");
if(StringUtils.isNotBlank(attachmentId)){
bool = attachmentService.deleteAttachment(attachmentId);
logger.info("刪除:"+bool);
}
if(bool>0){
json.put("result", "SUCCESS");
}else{
logger.info("刪除失敗");
json.put("result", "FAIL");
}
super.responseWriteJson(json, response);
return null;
}
@RequestMapping("/fileUpload.jhtml")
public String fileUpload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
//String root = request.getSession().getServletContext().getRealPath("/");
//logger.info("系統根目錄:"+root);
JSONObject result = null;
//創建一個通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判斷 request 是否有文件上傳,即多部分請求
if(multipartResolver.isMultipart(request)){
//轉換成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
//記錄上傳過程起始時的時間,用來計算上傳時間
int pre = (int) System.currentTimeMillis();
//取得上傳文件
MultipartFile file = multiRequest.getFile(iter.next());
String contentType = file.getContentType();
logger.info("獲取文件類型:"+contentType);
if(file != null){
result = new JSONObject();
//取得當前上傳文件的文件名稱
String myFileName = file.getOriginalFilename();
// 擴展名
String extName ="";
//如果名稱不爲“”,說明該文件存在,否則說明該文件不存在
if(myFileName.trim() !=""){
if (myFileName.lastIndexOf(".") >= 0) {
extName = myFileName.substring(myFileName.lastIndexOf("."));
}else{
extName = ".jpg";
}
UserVo user = getCurrentUser(request);
String dateName = DateUtils.date2String(new Date(),"yyyyMMddHHmmssSSS");
//重命名上傳後的文件名 定義上傳路徑 XXX/課題組Id/用戶ID/xxx.doc
String path = user.getCurrentPtid()+"/"+ user.getUserId()+"/"+dateName+extName;
String storePath =Constant.FILE_PATH+"/"+path;
logger.info("文件存儲路徑:"+storePath);
File localFile = new File(storePath);
if(!localFile.exists()){
localFile.mkdirs();
}
file.transferTo(localFile);// 寫入到指定服務器地址
result.put("fileName", myFileName);// 原始名稱
result.put("filePath", path);
result.put("fileId",IdGenerator.genUUid());// 文件ID 返回到前臺
logger.info("原文件名:"+myFileName+", 重命名爲:"+dateName+extName+", 文件路徑:"+path);
/*boolean bool = isImage(file);
if(bool){
// 原圖所在目錄
String thumbnail = user.getCurrentPtid()+"/"+ user.getUserId()+"/";
// 返回縮略圖地址
String thumbnailPath = ResizeImage.getResizeImage(path,thumbnail,0.125f);
logger.info("縮略圖地址:"+thumbnailPath);
}*/
responseWriteJson(result,response);
}
}
//記錄上傳該文件後的時間
int finaltime = (int) System.currentTimeMillis();
logger.info("上傳用時:" + (finaltime - pre)+"毫秒");
}
}
return null;
}
@RequestMapping("/kinderfileUpload.jhtml")
public String kinderfileUpload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
//String root = request.getSession().getServletContext().getRealPath("/");
//logger.info("系統根目錄:"+root);
JSONObject result = null;
//創建一個通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判斷 request 是否有文件上傳,即多部分請求
if(multipartResolver.isMultipart(request)){
//轉換成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
//記錄上傳過程起始時的時間,用來計算上傳時間
int pre = (int) System.currentTimeMillis();
//取得上傳文件
MultipartFile file = multiRequest.getFile(iter.next());
if(file != null){
result = new JSONObject();
//取得當前上傳文件的文件名稱
String myFileName = file.getOriginalFilename();
// 擴展名
String extName ="";
//如果名稱不爲“”,說明該文件存在,否則說明該文件不存在
if(myFileName.trim() !=""){
if (myFileName.lastIndexOf(".") >= 0) {
extName = myFileName.substring(myFileName.lastIndexOf("."));
}
UserVo user = getCurrentUser(request);
String dateName = DateUtils.date2String(new Date(),"yyyyMMddHHmmssSSS");
//重命名上傳後的文件名 定義上傳路徑 XXX/課題組Id/用戶ID/xxx.doc
String path = user.getCurrentPtid()+Constant.KINDERIMAGE+ user.getUserId()+"/"+dateName+extName;
String storePath =Constant.FILE_PATH+"/"+path;
logger.info("文件存儲路徑:"+storePath);
File localFile = new File(storePath);
if(!localFile.exists()){
localFile.mkdirs();
}
file.transferTo(localFile);// 寫入到指定服務器地址
result.put("fileName", myFileName);// 原始名稱
result.put("filePath", path);
result.put("fileId",IdGenerator.genUUid());// 文件ID 返回到前臺
logger.info("原文件名:"+myFileName+", 重命名爲:"+dateName+extName+", 文件路徑:"+path);
JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("url",Constant.IMAGE_RETURNURL+"/"+path);
responseWriteJson(obj,response);
}
}
//記錄上傳該文件後的時間
int finaltime = (int) System.currentTimeMillis();
logger.info("上傳用時:" + (finaltime - pre)+"毫秒");
}
}
return null;
}
//ueditor 上傳返回數據
// {"state": "SUCCESS","title": "1425972559231041214.jpg","original": "5.jpg","type": ".jpg","url": "/js/ueditor/jsp/upload/image/20150310/1425972559231041214.jpg","size": "483703"}
/**
* 批量下載
* @return
*/
@RequestMapping("/batchDownload.jhtml")
public String batchDownload(HttpServletRequest request,HttpServletResponse response){
String reladtedIds = request.getParameter("relatedIds");
String[] relatedIdArr = null;
if(StringUtils.isNotBlank(reladtedIds)){
relatedIdArr= reladtedIds.split(",");
}
// 根據ID查詢附件集合
List< AttachmentVo> attachmentList= attachmentService.getAttachmentByIdArray(relatedIdArr);
// 附件個數
logger.info("記錄數:"+relatedIdArr.length+" ,附件個數:"+attachmentList.size());
return null;
}
public boolean isImage(MultipartFile file) {
List<String> allowType = Arrays.asList("image/bmp","image/png","image/gif","image/jpg","image/jpeg","image/pjpeg");
return allowType.contains(file.getContentType());
}
/**
*
* @param request
* @param response
*/
public void getZip(HttpServletRequest request,HttpServletResponse response){
// 附件名稱
String attachmentName ="doc文檔.zip";
// 打包後的zip文件路徑
String path = Constant.FILE_PATH+attachmentName;
logger.info("zip包文件臨時路徑:"+path);
// 待打包文件路徑
String[] arr = new String[]{"D:\\ws\\文檔\\20141031","D:\\ws\\文檔\\20141029\\IT運維發佈系統改造使用說明2.docx"};
ZipUtils.createZip(arr, path);
// 開始下載
this.downFile(response,path,attachmentName);
}
/**
* 根據附件ID下載
* @throws Exception
*/
@RequestMapping("/singleDownload.jhtml")
private void downFile(HttpServletRequest request,HttpServletResponse response) throws Exception {
AttachmentVo attachmentVo= attachmentService.getAttachmentById(request.getParameter("attachmentId"));
if (attachmentVo==null) {
return ;
}
// 用戶獲取文件大小
FileChannel fileChanel = null;
FileInputStream ins =null;
InputStream bins =null;
OutputStream outs = null;
BufferedOutputStream bouts =null;
try {
ins = new FileInputStream(Constant.FILE_PATH+"/"+attachmentVo.getFilePath());
bins = new BufferedInputStream(ins);// 放到緩衝流裏面
outs = response.getOutputStream();// 獲取文件輸出IO流
bouts = new BufferedOutputStream(outs);
response.setContentType("application/x-download");// 設置response內容的類型
response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(attachmentVo.getFileName(), "UTF-8"));// 設置頭部信息
fileChanel = ins.getChannel();
response.setContentLength((int) fileChanel.size());
logger.info("下載文件大小:"+fileChanel.size()/1000 +"KB");
int bytesRead = 0;
byte[] buffer = new byte[1024*2];
// 開始向網絡傳輸文件流
while ((bytesRead = bins.read(buffer, 0, 1024*2)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();// 這裏一定要調用flush()方法
} catch (IOException e) {
JSONObject json = new JSONObject();
logger.error("文件下載出錯", e);
if(e instanceof FileNotFoundException){
logger.info("下載的資源文件不存在");
json.put("desc", "您請求下載的資源文件不存在!");
responseWriteJson(json, response);
}
}finally{
try {
if(null!=ins){
ins.close();
}
if(null!=bins){
bins.close();
}
if(null!=outs){
outs.close();
}
if(null!=bouts){
bouts.close();
}
} catch (IOException e) {
logger.info("關閉流異常",e);
e.printStackTrace();
}
}
}
/**
* 下載方法
* @param response
* @param path 文件路徑
* @param fileName 文件名
*/
private void downFile(HttpServletResponse response, String path,String fileName) {
try {
File file = new File(path);
if (file.exists()) {
InputStream ins = new FileInputStream(path);
BufferedInputStream bins = new BufferedInputStream(ins);// 放到緩衝流裏面
OutputStream outs = response.getOutputStream();// 獲取文件輸出IO流
BufferedOutputStream bouts = new BufferedOutputStream(outs);
response.setContentType("application/x-download");// 設置response內容的類型
response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));// 設置頭部信息
int bytesRead = 0;
byte[] buffer = new byte[8192];
// 開始向網絡傳輸文件流
while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();// 這裏一定要調用flush()方法
ins.close();
bins.close();
outs.close();
bouts.close();
} else {
PrintWriter out = response.getWriter();
out.write("<script>alert('download Error ! palease try again');window.location.href='page/home.jsp';</script>");
}
// 刪除臨時文件
if(file.exists()){
logger.info("開始刪除臨時壓縮文件包");
if(!file.delete()){
logger.info("刪除失敗");
}
}
} catch (IOException e) {
logger.error("文件下載出錯", e);
}
}
/**
* 判斷文件是否存在
* @throws Exception
*/
@RequestMapping("/isExists.jhtml")
private void isExists(HttpServletRequest request,HttpServletResponse response) throws Exception {
AttachmentVo attachmentVo= attachmentService.getAttachmentById(request.getParameter("attachmentId"));
JSONObject json = new JSONObject();
if (attachmentVo==null) {
logger.info("下載的資源文件不存在");
json.put("result", "0");// 不存在
json.put("desc", "您請求下載的資源文件不存在!");
}else {
File file = new File(Constant.FILE_PATH+"/"+attachmentVo.getFilePath());
if(!file.exists()){
logger.info("服務器沒有該資源文件或已被刪除");
json.put("result", "0");// 不存在
json.put("desc", "您請求下載的資源文件不存在!");
}
}
responseWriteJson(json, response);
}
}