container" >pickfiles">
filelist" style="width: 100%;">
---------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(""+ ");
""+file.name +"(" + plupload.formatSize(file.size) + ") "+
""+new Date().format("yyyy-MM-dd hh:mm")+" "+
"移除 "+
"
});
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(""+
"");
//$("#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(""+ ");
""+file.name +"(" + plupload.formatSize(file.size) + ") "+
""+new Date().format("yyyy-MM-dd hh:mm")+" "+
"移除 "+
"
});
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(""+
""+
"");
//$("#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: ''+msg+''});
d.showModal();
}
/**
* alert提示(time毫秒后自动关闭)
* @param msg
* @return
*/
function showalertTime(msg,time){
var d = dialog({title: '提示',width:'200',height:'50', content: ''+msg+''});
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
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
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
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("");
}
// 删除临时文件
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);
}
}