package com.tkb.daboweb.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ssh.spring.DeployInfoUtil;
import app.j2ee.data.RandKeyCreator;
import app.j2ee.file.FileUtil;
import app.other.commons.file.MutiFileUpload;
import app.other.poi.excel.ExcelUtil;
public class FileTempUtil {
private static final Log log = LogFactory.getLog(FileTempUtil.class);
public static String getParam(String param, Map map){
String temp = "";
if(map != null){
Object o = map.get(param);
if (o != null) {
temp = (String)o;
try {
temp = new String(temp.getBytes("iso-8859-1"), "utf8");
} catch (Exception e) {
// TODO: handle exception
}
}
}
return temp.trim();
}
//接收Integer
public static Integer getIntParam(String param, Map map,Integer defaultValue){
int num = defaultValue;
if(map != null){
Object o = map.get(param);
if (o != null) {
try {
o = new String(((String)o).getBytes("iso-8859-1"), "utf8");
num = Integer.parseInt((String)o);
} catch (Exception e) {
}
}
}
return num;
}
//接收Date yyyy-MM-dd
public static Date getDateParam(String param, Map map){
String temp = getParam(param, map);
Date date = null;
if(!temp.equals("")){
date = DataFormater.getDate(temp + " 00:00:00", DataFormater.DATATIME_STR);
}
return date;
}
/**
* 取得普通表單數據
* @param request
* @return
*/
public static Map getPreParameters(MutiFileUpload upload){
return upload.parameters;
}
/**
* 多文件上傳
* 返回 上傳文件路徑 及 原始檔案名
*
* folder 文件夹
* id 文件夹
* isRandom,是否用随机数
*
* return map
* key-oldXXX(原文件名), newXXX(新文件名), XXX(虚拟文件名)
*/
public static Map<String,String> upload(MutiFileUpload upload, String folder, String id, boolean isRandom) throws Exception {
Map<String,String> temp = new HashMap<String,String>();
String rootPath = DeployInfoUtil.getUploadFilePath() + ConstantsUtil.UPLOADFILE_PATH + File.separator +
folder + File.separator;
String virtualPath = ConstantsUtil.UPLOADFILE_PATH + File.separator +folder + File.separator;
Iterator iterator = upload.files.values().iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (upload.getFileName(item) == null
|| upload.getFileName(item).equals(""))
continue;
String rankKey = RandKeyCreator.getRandStr(12);
String fileName = upload.getFileName(item); //原來的檔案名
String fileType = fileName.substring(fileName.lastIndexOf("."),fileName.length());
String fieldName = item.getFieldName();
//設置原始檔案名
temp.put("old"+fieldName, fileName); //原始文件名称 abc.jpg
if(isRandom){
fileName = rankKey+fileType;
}
temp.put("new" + fieldName, fileName); //随机文件名 3434343434a.jpg
FileUtil.saveFile(rootPath + id + File.separator ,fileName, item.get());
fileName = virtualPath + id + File.separator + fileName;
temp.put(fieldName, fileName.replace("\\", "/")); //url文件名 upload/news/1/3434343434a.jpg
}
return temp;
}
/**
* 多文件上傳
* @param request
* @param folder 資源文件 如,game
* @param id 表中id
* @param files game下面二級目錄如game、pic 若沒有則null
* @return
* @throws Exception
*/
public static Map<String,String> upload(MutiFileUpload upload, String folder, String id, String [] files) throws Exception {
Map<String,String> temp = new HashMap<String,String>();
String rootPath = DeployInfoUtil.getUploadFilePath() + ConstantsUtil.UPLOADFILE_PATH + File.separator +
folder + File.separator;
String virtualPath = ConstantsUtil.UPLOADFILE_PATH + File.separator +folder + File.separator;
Iterator iterator = upload.files.values().iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (upload.getFileName(item) == null
|| upload.getFileName(item).equals(""))
continue;
String rankKey = RandKeyCreator.getRandStr(12);
String fileName = upload.getFileName(item); //原來的檔案名
String fieldName = item.getFieldName();
if(files == null){
FileUtil.saveFile(rootPath + id + File.separator + rankKey,fileName, item.get());
fileName = virtualPath + id + File.separator + rankKey + File.separator + fileName;
temp.put(fieldName, fileName.replace("\\", "/"));
}else{
for(String file:files){
if(file.equals(fieldName)){
FileUtil.saveFile(rootPath + file + File.separator + id + File.separator + rankKey,
fileName, item.get());
fileName = virtualPath + file + File.separator + id + File.separator + rankKey + File.separator + fileName;
temp.put(fieldName, fileName.replace("\\", "/"));
break;
}
}
}
}
return temp;
}
public static void delFile(String fileName) throws Exception{
String filePath = fileName.substring(0,fileName.lastIndexOf("/"));
filePath = fileName.substring(0,filePath.lastIndexOf("/"));
filePath = DeployInfoUtil.getUploadFilePath() + filePath.replace("/", "\\");
FileUtil.delAll(new File(filePath));
}
public static void delUpdateFile(String fileName) throws Exception{
String filePath = fileName.substring(0,fileName.lastIndexOf("/"));
filePath = DeployInfoUtil.getUploadFilePath() + filePath.replace("/", "\\");
FileUtil.delAll(new File(filePath));
}
//add by zhangmingshuang ---------2012-02-21
public static void delFilePost(String fileName) throws Exception{
String filePath = fileName.substring(0,fileName.lastIndexOf("/"));
filePath = DeployInfoUtil.getUploadFilePath() + filePath.replace("/", "\\");
FileUtil.delAll(new File(filePath));
}
public static void delUpdateFilePost(String fileName) throws Exception{
String filePath = DeployInfoUtil.getUploadFilePath() + fileName.replace("/", "\\");
FileUtil.delAll(new File(filePath));
}
/**
* 文件長度單位處理
* @param orilength
* @return
*/
public static String getFileSizeHandle(long orilength){
DecimalFormat df = new DecimalFormat( "0.## ");
if(orilength < 1024){
return orilength+"B";
}else if(orilength < 1024*1024){
Float si=orilength/1024f;
return df.format(si)+"KB";
}else{
Float si=orilength/1024f/1024f;
return df.format(si)+"M";
}
}
/**
* 下載
* @param request
* @param response
* @param path 路径Z:\huayuschool\
* @param fileName 文件名
* @throws Exception
* @return loadFlag ---true 下載成功, false 下載失敗
*/
public static boolean download(HttpServletRequest request, HttpServletResponse response, String path, String fileName) throws Exception{
boolean loadFlag = true; //下載成功標志位
File file = null;
InputStream in = null; // 輸入流
OutputStream out = null; // 輸出流
//在下載附件之前設置響應類型和頭部文件
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(ExcelUtil.subLastStr(fileName, "/"),"UTF-8"));
try{
file = new File(path); //取得文件對像
//從下載附件創建輸入流,并向請求獲取并寫入(客戶端或網絡)輸出流
in = new BufferedInputStream(new FileInputStream(file));
out = response.getOutputStream();
int readSize = 1024 * 10; //讀取大小
int length = 0; //讀取剩余大小
byte[] readByte = new byte[readSize];
while ((length = in.read(readByte, 0, readSize)) != -1) {
out.write(readByte, 0, length);
}
out.flush();
}catch(Exception e){
loadFlag = false;
e.printStackTrace();
}finally{
if(in!=null || out!=null ){
try {
in.close();
out.close();
} catch (IOException e) {
loadFlag = false;
e.printStackTrace();
}
}
}
return loadFlag;
}
}