一 单个文件下载
1.1 jsp部分
<form action="${ctx}/knowledgeBase/fileManage/downLoadDocument" id="downLoadForm">
<input type="hidden" name="filePath" id="filePath" />
</form>
$("#downLoadForm").submit();
1.2 后台
@RequestMapping(value = "/downLoad", method = RequestMethod.GET)
public void fileDownLoad(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String filePath = new String(request.getParameter("filePath").getBytes("iso8859-1"),
"UTF-8");
String scritpId = request.getParameter("scriptId");
scritpId = "('"+scritpId+"')";
String fileName = String.valueOf(request.getParameter("fileName"));
fileName = URLDecoder.decode(fileName , "utf-8");
// boolean bl = false;
if (response != null && request != null && filePath != null && !filePath.equals("")) {
String browserType = request.getParameter("browserType");
final String userAgent = request.getHeader("USER-AGENT");
// filePath是指欲下载的文件的路径。
filePath = URLDecoder.decode(filePath, "UTF-8");
File file = new File(filePath);
if (!file.exists()) {
//throw new Exception("文件不存在!");
request.getRequestDispatcher(
"/WEB-INF/views/msunsoft/knowledgeBase/fileError.jsp")
.forward(request, response);
return;
}
if (!file.isFile()) {
throw new Exception("非文件类型!");
}
// 取得文件名。
if ("IE".equals(browserType)) {// IE浏览器,页面传过来的值,只用于判断是否为IE浏览器
// logger.info("ie浏览器");
fileName = URLEncoder.encode(fileName, "UTF8");
} else {
if (userAgent.contains("Mozilla")) {// google,火狐浏览器
fileName = new String(fileName.getBytes(), "ISO8859-1");
//logger.info("火狐浏览器");
} else {
// logger.info("其他浏览器");
fileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
}
}
// 提示框设置
response.reset(); // reset the response
// response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");//告诉浏览器输出内容为流
response.setHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
//读出文件到i/o流
FileInputStream fis = new FileInputStream(file);
BufferedInputStream buff = new BufferedInputStream(fis);
byte[] ary_byte = new byte[1024];//缓存
long k = 0;//该值用于计算当前实际下载了多少字节
// 输出流
OutputStream out = response.getOutputStream();
//开始循环下载
while (k < file.length()) {
int j = buff.read(ary_byte, 0, 1024);
k += j;
//将b中的数据写到客户端的内存
out.write(ary_byte, 0, j);
}
// 关闭输出流
if (out != null) {
out.flush();
out.close();
fis.close();
buff.close();
}
//添加下载次数
List<KowledgeBase> numberList = knowledgeBaseDao.findDownLoadNumber(scritpId);
if(numberList.size()>0) {
knowledgeBaseDao.addDownloadNumber(numberList);
}
//logger.info("文件下载完毕!");
} else {
new NullPointerException(
"HttpServletRequest Or HttpServletResponse Or fileName Is Null !");
}
}
二 批量下载成压缩包
2.1 jsp部分
<form action="${ctx}/knowledgeBase/fileManage/downLoadDocument" id="downLoadForm">
<input type="hidden" name="ids" id="ids" />
</form>
$("#downLoadForm").submit();
2.2 后台部分
@RequestMapping(value = "/downLoadDocument", produces = "text/json;charset=UTF-8")
public void downLoadDocument(HttpServletRequest request, HttpSession session,
HttpServletResponse response) throws IOException {
String ids = request.getParameter("ids");
ids = "('"+ids+"')";
Map<String, Object> file = null;
try {
String ZIP_PATH ="";
file = fileRecordService.selectDocumentList(ids, ZIP_PATH);
} catch (Exception e) {
try {
//log.info("文件压缩失败:" + e.getMessage());
System.out.println("文件压缩失败:" + e.getMessage());
response.getWriter().write(e.getMessage());
e.printStackTrace();
request.getRequestDispatcher(
"/WEB-INF/views/msunsoft/knowledgeBase/fileError.jsp")
.forward(request, response);
return;
} catch (ServletException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
if (file != null) {
List<File> list = (List<File>) file.get("orgList");
for (File file2 : list) {
try {
FileZipUtil.deleteDir(file2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
if (file != null) {
if (file.get("fileZip") != null) {
downloadZip((File) file.get("fileZip"), response);
}else {
try {
request.getRequestDispatcher(
"/WEB-INF/views/msunsoft/knowledgeBase/fileError.jsp")
.forward(request, response);
} catch (ServletException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
//添加下载次数
List<KowledgeBase> numberList = knowledgeBaseDao.findDownLoadNumber(ids);
if(numberList.size()>0) {
knowledgeBaseDao.addDownloadNumber(numberList);
}
}
}
public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
try {
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
//如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
File f = new File(file.getPath());
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
2.3 service层FileRecordService
/**
* Project Name:bph_sp<br>
* File Name:FileRecordServiceImpl.java<br>
* Package Name:com.msunsoft.bph_sp.specialSupervision.documentManage.service.impl<br>
* Date:2017-12-3下午1:21:29<br>
* Copyright (c) 2017, MSunSoft All Rights Reserved.
*
*/
package com.msunsoft.knowledgeBase.base.service;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.msunsoft.common.utils.file.FileZipUtil;
import com.msunsoft.knowledgeBase.base.dao.FileRecordDao;
import com.msunsoft.knowledgeBase.base.entity.FileRecord;
import com.msunsoft.knowledgeBase.base.entity.FileRecordGroup;
/**
*
* @author
* @date 2017-12-3 下午1:21:29
* @description
*/
@Service
public class FileRecordService {
@Autowired
private FileRecordDao fileRecordMapper;
public List<FileRecord> selectByExample(Map<String, String> map) {
// TODO Auto-generated method stub
return fileRecordMapper.selectByExample(map);
}
public int insert(FileRecord record) {
// TODO Auto-generated method stub
return fileRecordMapper.insert(record);
}
public boolean delectFile(FileRecord record ) throws Exception {
String realPath = record.getRealPath();
//realPath =realPath.replace("/", "\\");
String htmlPath = record.getHtmlPath();
File file = new File(realPath);
if (file.exists()) {
file.delete();
if (StringUtils.isNotBlank(htmlPath)) {
File htmlFile = new File(htmlPath);
htmlFile.delete();
}
}
return true;
}
public void deleteScript(FileRecord record ) {
fileRecordMapper.delectById(record.getId());
}
/**
* 批量删除
* @param ids
*/
public void deleteScriptByIds(String ids ) {
fileRecordMapper.delectByIds(ids);
}
public FileRecord selectById(String id) {
return fileRecordMapper.selectById(id);
}
/**
* 判断文件是否存在
* @param orgs
* @param indexs
* @param year
* @param path
* @return map ORG_CODE,ORG_NAME,REAL_PATH,FILE_NAME
* @throws IOException
*/
public Map<String, Object> checkDocumentExist( String ids) throws IOException {
Map<String, Object> resultMap = new HashMap<String, Object>();
//不存在的文件集合
List<FileRecord> fileNotExistList = new ArrayList<FileRecord>();
List<FileRecord> nameList = new ArrayList<FileRecord>();
boolean hasDownLoadFile = false;//是否有可下载的文件(文件是否丢失)
List<File> fileList = new ArrayList<File>();
//查询出所有当前查询条件的文件信息
List<FileRecord> result = fileRecordMapper.selectByIds(ids);
if (result.size() > 0) {
for (FileRecord fileRecord : result) {
File file = new File(fileRecord.getRealPath());
fileList.add(file);
// nameList.add(map.get("FILE_NAME") + "");
nameList.add(fileRecord);
}
boolean thisItemCheck = checkFolerExist(fileList,nameList,fileNotExistList);
if(true == thisItemCheck) {
hasDownLoadFile = thisItemCheck;
}
}
resultMap.put("fileNotExistList", fileNotExistList);
resultMap.put("hasDownLoadFile", hasDownLoadFile);
return resultMap;
}
public boolean checkFolerExist(List<File> files,List<FileRecord> nameList,List<FileRecord> fileNotExistList) throws IOException{
boolean hasDownLoadFile = false;
for (int i = 0; i < files.size(); i++) {
boolean thisItemResult = checkFolerForFile(files.get(i),nameList.get(i), fileNotExistList);
if(true == thisItemResult) {
hasDownLoadFile = true;
}
}
return hasDownLoadFile;
}
/**
* 判断文件是否存在
* @param file
* @param newFileMap
* @param fileNotExistList
* @return
* @throws IOException
*/
public boolean checkFolerForFile(File file,FileRecord newFileMap,List<FileRecord> fileNotExistList) throws IOException{
if (!file.exists()) {
fileNotExistList.add(newFileMap);
// FileNotFoundException e = new FileNotFoundException("下载的文件" + newFileName + "不存在请联系技术支持!");
// throw e;
return false;
}else {
return true;//
}
}
/**
* 压缩文件
* @param orgs
* @param indexs
* @param year
* @param path
* @return
* @throws IOException
*/
public Map<String, Object> selectDocumentList(String ids, String path) throws IOException {
Map<String, Object> resultMap = new HashMap<String, Object>();
List<File> orgList = new ArrayList<File>();
// String baseFolder = path +"/下载";
// File orgfile = new File(baseFolder);
// orgfile.mkdirs();
//存放即将要进行压缩的文件集合
List<File> bigTypeList = null;
List<String> nameList = null;
//存放个地区大类压缩完成的文件
List<File> bigFileZipList = new ArrayList<File>();
//存放将要压缩的各大类的文件
bigTypeList = new ArrayList<File>();
nameList = new ArrayList<String>();
//查询大类
// List<FileRecord> bigTypeInfpList = fileRecordMapper.selectByIds(ids);
Map<String, FileRecordGroup> mapFile = fileRecordMapper.selectGroupType(ids);
//循环大类,将每个大类的文件放在一个文件夹
for(Map.Entry<String, FileRecordGroup> entry : mapFile.entrySet()){
String mapKey = entry.getKey();
String fileTypeName = getTypeNameByType(mapKey);
FileRecordGroup fileTypeGroup = entry.getValue();
List<FileRecord> listRecord = fileTypeGroup.getFileRecordList();
//大类里的文件
for(int i=0;i<listRecord.size();i++) {
FileRecord fileRecord = listRecord.get(i);
File file = new File(fileRecord.getRealPath());
bigTypeList.add(file);
nameList.add(fileRecord.getFileName());
}
String baseFolder = path +"/"+fileTypeName;
File orgfile = new File(baseFolder);
orgfile.mkdirs();
createFoler(bigTypeList, orgfile, nameList);
//将每个大类压缩的文件加入集合,准备再一次压缩
bigFileZipList.add(orgfile);
if (bigFileZipList.size() > 0) {
orgList.add(orgfile);
}else {//删除空的文件夹
FileZipUtil.deleteDir(orgfile);
}
}
File fileZip = null;
if (orgList.size() > 0) {
String fileName = String.valueOf(System.nanoTime());
fileZip = createDocumentZipFile(orgList, fileName, null);
}
resultMap.put("orgList", orgList);
resultMap.put("fileZip", fileZip);
return resultMap;
}
//1接口类2报表类3文档类4公卫类
public String getTypeNameByType(String fileType) {
if("1".equals(fileType)) {
return "接口类";
}else if("2".equals(fileType)) {
return "报表类";
}else if("3".equals(fileType)) {
return "文档类";
}else if("4".equals(fileType)) {
return "公卫类";
}else {
return "其他";
}
}
public void createFoler(List<File> files, File toFile, List<String> nameList ) throws IOException{
for (int i = 0; i < files.size(); i++) {
createFolderForFile(files.get(i), toFile,nameList.get(i) );
}
}
public File createFolderForFile(File file, File toFile, String newFileName ) throws IOException{
byte[] b = new byte[1024];
int a;
FileInputStream fis = null ;
FileOutputStream fos = null ;
toFile.mkdirs();
if (file.isDirectory()) {
String filepath = file.getAbsolutePath();
filepath = filepath.replaceAll("\\\\", "/");
String toFilepath = toFile.getAbsolutePath();
toFilepath = toFilepath.replaceAll("\\\\", "/");
int lastIndexOf = filepath.lastIndexOf("/");
toFilepath = toFilepath + filepath.substring(lastIndexOf, filepath.length());
File copy = new File(toFilepath);
// //复制文件夹
if (!copy.exists()) {
copy.mkdirs();
}
//遍历文件夹
for (File f : file.listFiles()) {
createFolderForFile(f, copy, f.getName() );
}
} else {
if (toFile.isDirectory()) {
String filepath = file.getAbsolutePath();
filepath = filepath.replaceAll("\\\\", "/");
String toFilepath = toFile.getAbsolutePath();
toFilepath = toFilepath.replaceAll("\\\\", "/");
// int lastIndexOf = filepath.lastIndexOf("/");
toFilepath = toFilepath + "/" + newFileName;
//写文件
File newFile = new File(toFilepath);
if (file.exists()) {
fis = new FileInputStream(file);
fos = new FileOutputStream(newFile);
while ((a = fis.read(b)) != -1) {
fos.write(b, 0, a);
}
fis.close();
fos.close();
}
} else {
//写文件
fis = new FileInputStream(file);
fos = new FileOutputStream(toFile);
while ((a = fis.read(b)) != -1) {
fos.write(b, 0, a);
}
fis.close();
fos.close();
}
}
return null;
}
public File createDocumentZipFile(List<File> files, String fileName, List<String> nameList)
throws IOException {
//临时文件存放路径
File file = new File("E:/" + fileName + ".rar");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
//创建文件输出流
FileOutputStream fous = new FileOutputStream(file);
/**
* 打包的方法我们会用到ZipOutputStream这样一个输出流, 所以这里我们把输出流转换一下
*/
ZipOutputStream zipOut = new ZipOutputStream(fous);
for (int i = 0; i < files.size(); i++) {
writeZip(files.get(i), "", zipOut);
}
zipOut.close();
fous.close();
return file;
}
private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
if (file.exists()) {
if (file.isDirectory()) {//处理文件夹
parentPath += file.getName() + File.separator;
File[] files = file.listFiles();
if (files.length != 0) {
for (File f : files) {
writeZip(f, parentPath, zos);
}
} else { //空目录则创建当前目录
try {
zos.putNextEntry(new ZipEntry(parentPath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
FileInputStream fis = null;
try {
FileInputStream IN = new FileInputStream(file);
BufferedInputStream bins = new BufferedInputStream(IN, 512);
//org.apache.tools.zip.ZipEntry
// if (newFileName!=null) {
// ZipEntry entry = new ZipEntry(newFileName);
// ouputStream.putNextEntry(entry);
// }else{
ZipEntry entry = new ZipEntry(parentPath + file.getName());
zos.putNextEntry(entry);
//}
// 向压缩文件中输出数据
int nNumber;
byte[] buffer = new byte[512];
while ((nNumber = bins.read(buffer)) != -1) {
zos.write(buffer, 0, nNumber);
}
// 关闭创建的流对象
bins.close();
IN.close();
} catch (FileNotFoundException e) {
// log.error("创建ZIP文件失败", e);
System.out.println("创建ZIP文件失败"+e);
} catch (IOException e) {
//log.error("创建ZIP文件失败", e);
System.out.println("创建ZIP文件失败"+e);
} finally {
try {
if (fis != null) {
fis.close();
zos.close();
}
} catch (IOException e) {
//log.error("创建ZIP文件失败", e);
System.out.println("创建ZIP文件失败"+e);
}
}
}
}
}
}