package com.infrastructure.project.common.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.infrastructure.project.common.SysConstant;
public class DownLoadUtil {
/**
*
* @param response
* @param request
* @param filePath
* @param fileName
* @param type
* @throws IOException
*/
public static void downLoad(HttpServletResponse response,HttpServletRequest request,String filePath ,String fileName,String type) throws IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
try {
File file = null;
if(SysConstant.downLoadType.DOWNLOAD_PDF.equals(type) || type == SysConstant.downLoadType.DOWNLOAD_PDF){
file = new File(filePath+fileName+SysConstant.nameSuffix.NAMESUFFIX_PDF);
}else if(SysConstant.downLoadType.DOWNLOAD_EXCEL.equals(type) || type == SysConstant.downLoadType.DOWNLOAD_EXCEL){
file = new File(filePath+fileName+SysConstant.nameSuffix.NAMESUFFIX_EXCEL);
}else if(SysConstant.downLoadType.DOWNLOAD_WORD.equals(type) || type == SysConstant.downLoadType.DOWNLOAD_WORD){
file = new File(filePath+fileName+SysConstant.nameSuffix.NAMESUFFIX_WORD);
}else if(SysConstant.downLoadType.DOWNLOAD_ZIP.equals(type) || type == SysConstant.downLoadType.DOWNLOAD_ZIP){
file = new File(filePath+fileName+SysConstant.nameSuffix.NAMESUFFIX_ZIP);
}else if(SysConstant.downLoadType.DOWNLOAD_TXT.equals(type) || type == SysConstant.downLoadType.DOWNLOAD_TXT){
file = new File(filePath+fileName+SysConstant.nameSuffix.NAMESUFFIX_TXT);
}else{
file = new File(filePath+fileName+SysConstant.nameSuffix.NAMESUFFIX_HTML);
}
long fileLength = file.length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename="+ new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
}