package com.hundsun.emall.common.util;
import java.awt.Image;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import com.hundsun.oss.OssService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.apache.poi.hssf.usermodel.HSSFCell;
//import org.apache.poi.hssf.usermodel.HSSFCellStyle;
//import org.apache.poi.hssf.usermodel.HSSFFont;
//import org.apache.poi.hssf.usermodel.HSSFRow;
//import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.hundsun.jresplus.common.util.DateUtil;
import com.hundsun.jresplus.common.util.StringUtil;
/**
* @author wuyb
* @version $Id: FileUploadUtil.java,v 0.1 2010-7-22 下午04:51:53 wuyb Exp $
*/
public class FileUploadUtil {
private Log log = LogFactory.getLog(getClass());
public static final String SEP = "/";
public static final String POINT = ".";
public static final String[] EXTARRAY = { "jpg", "jpeg", "gif", "png", "mkv","wmv" ,"mp4","rmvb","MOV"};
public static final String[] EXTARRAY_IMG = { "jpg", "jpeg", "gif", "png"};
public static final String[] EXTARRAY_VIDEO = { "mkv","wmv" ,"mp4","rmvb","MOV"};
public static final String[] EXTARRAY_EXCEL = { "xls","xlsx"};// excel格式暂时只支持03版
public static final String[] ExTARRAY_ALL ={"jpg", "jpeg", "gif", "png","zip","rar","pdf"};
public static final String[] ExTARRAY_OK ={"jpg", "png","pdf","doc","docx","rar","zip", "jpeg", "gif"};
public static final String TYPE_IMG = "img";
public static final String TYPE_EXCEL = "excel";
public static final String TYPE_VIDEO = "video";
public String fileUploadDir;//对应oss bucket下的第一级目录
public static final int MAX_FILE_SIZE = 200 * 1024; //最大文件尺寸200k
public static final String CRM_PIC_PATH = "000000";
public static final String UNLOGIN_USER_PIC_PATH = "posgoo";
//施工单位表单提交
public static final String sgform = "sgform";
//设计单位表单提交
public static final String sjform = "sjform";
//监理单位表单提交
public static final String jlform = "jlform";
//上传导入文件
public static final String importfile = "importfile";
//施工单位审核流程上传附件
public static final String sg_attachment = "sg_attachment";
//意见附件
public static final String yijian_attachment = "yijian_attachment";
// 单位回收证明资料
public static final String rollback_evidence = "rollback_evidence";
public static final String ckedit = "ckedit";
//信用系统上传附件
public static final String CRFORM = "crform";
/**
*溯源档案操作内容
*/
public static final String TRACE_FILE_OPERATION = "operation";
/**
* 活动标识图上传目录名
*/
public static final String ACTIVITY_FILE_HOME_DIR = "activity";
/**
* 招商入驻证书照片上传目录名
*/
public static final String COMPANY_LICENSE_HOME_DIR = "company";
/**
* 开店身份证正反面扫描件上传目录名
*/
public static final String SHOP_IDCARD_HOME_DIR = "idcard";
/**
* LOGO
*/
public static final String LOGO = "logo";
/**
* 溯源
*/
public static final String TRACE_DIR = "trace";
/**
* 文件流格式,根据文件流中特定的一些字节标识来区分不同类型的文件
*/
public final static Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>();
/**
* 判断上传的文件大小是否小于指定值
* @param file
* @return
*/
public static boolean ifFileSizePermitted(MultipartFile file) {
return file.getSize() < MAX_FILE_SIZE ? true : false;
}
/**
* 判断上传的文件大小是否小于指定值
* @param file,max_file_size文件大小限制值
* @return
*/
public static boolean ifFileSizePermitted(MultipartFile file,int MAX_FILE_SIZE) {
if(file==null){
return true;
}
return file.getSize() < MAX_FILE_SIZE ? true : false;
}
/**
* 判断上传的文件扩展名是否合法
* @param file
* @return
* @throws Exception
*/
public static boolean ifExtendNamePermitted(MultipartFile file) {
if(file==null){
return true;
}
String orgFileName = file.getOriginalFilename();
if (StringUtil.isBlank(orgFileName)) {
//如果传的是空文件
return true;
}
//文件流 判断后缀
try {
FILE_TYPE_MAP.clear();
getFileType();
InputStream is = file.getInputStream();
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
for (int i = 0; i < 10; i++) {
int a = is.read();
bytestream.write(a);
}
byte imgdata[]=bytestream.toByteArray();
if (getFileTypeByStream(imgdata) == null) {
// throw new Exception("不是指定类型文件!");
//不是指定文件返回
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
String exts = orgFileName.substring(orgFileName.lastIndexOf(".") + 1, orgFileName.length());
return ifExtendNamePermitted(exts);
}
public static String getFileTypeByStream(byte[] b) {
String filetypeHex = String.valueOf(getFileHexString(b));
System.out.println(filetypeHex);
Iterator<Entry<String, String>> entryiterator = FILE_TYPE_MAP
.entrySet().iterator();
while (entryiterator.hasNext()) {
Entry<String, String> entry = entryiterator.next();
String fileTypeHexValue = entry.getValue().toUpperCase();
if (filetypeHex.toUpperCase().startsWith(fileTypeHexValue)) {
return entry.getKey();
}
}
return null;
}
public static String getFileHexString(byte[] b) {
StringBuilder stringBuilder = new StringBuilder();
if (b == null || b.length <= 0) {
return null;
}
for (int i = 0; i < b.length; i++) {
int v = b[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
public static void getFileType() {
FILE_TYPE_MAP.put("jpg", "FFD8FF"); // JPEG (jpg)
FILE_TYPE_MAP.put("jpeg", "FFD8FF"); // JPEG (jpg)
FILE_TYPE_MAP.put("png", "89504E47"); // PNG (png)
FILE_TYPE_MAP.put("gif", "47494638"); // GIF (gif)
FILE_TYPE_MAP.put("mov", "00000014667479707174"); // Quicktime (mov)
FILE_TYPE_MAP.put("rmvb", "2e524d46000000120001"); // rmvb
FILE_TYPE_MAP.put("mp4", "00000020667479706d70");
FILE_TYPE_MAP.put("wmv", "3026b2758e66CF11a6d9");
FILE_TYPE_MAP.put("mkv", "1a45dfa3010000000000");
FILE_TYPE_MAP.put("xls", "D0CF11E0"); // WORD/EXCEL
}
public static boolean ifExtendNamePermitted(String exts) {
for (String s : EXTARRAY) {
if (exts.equalsIgnoreCase(s)) {
return true;
}
}
return false;
}
public static boolean ifExtendAllNamePermitted(String exts) {
for (String s : ExTARRAY_OK) {
if (exts.equalsIgnoreCase(s)) {
return true;
}
}
return false;
}
public static boolean ifExtendNamePermitted(String exts,String type) {
if("img".equals(type)){
for (String s : EXTARRAY_IMG) {
if (exts.equalsIgnoreCase(s)) {
return true;
}
}
}else if("video".equals(type)){
for (String s : EXTARRAY_VIDEO) {
if (exts.equalsIgnoreCase(s)) {
return true;
}
}
}else if("excel".equals(type)){
for (String s : EXTARRAY_EXCEL) {
if (exts.equalsIgnoreCase(s)) {
return true;
}
}
}
return false;
}
public boolean ifImgSize(MultipartFile file,int width,int height){
Image src;
try {
src = ImageIO.read(file.getInputStream());
int srcWidth = src.getWidth(null);
int srcHeight = src.getHeight(null);
if(srcWidth>width||srcHeight>height){
return false;
}
} catch (IOException e) {
log.error("FileUploadUtil.ifImgSize"+e, e);
return false;
}
return true;
}
public static boolean ifExtendNamePermitt(MultipartFile file,String extendName) {
String orgFileName = file.getOriginalFilename();
if (StringUtil.isBlank(orgFileName)) {
//如果传的是空文件
return true;
}
String exts = orgFileName.substring(orgFileName.lastIndexOf(".") + 1, orgFileName.length());
return ifExtendNamePermitt(exts,extendName);
}
public static boolean ifExtendNamePermitt(String exts,String extendName) {
if (exts.equalsIgnoreCase(extendName)) {
return true;
}
return false;
}
public String uploadFile(MultipartFile file, String userId, String destDir) {
if (StringUtil.isBlank(userId)) {
return uploadFile(file, UNLOGIN_USER_PIC_PATH + SEP + destDir);
}
return uploadFile(file, userId + SEP + destDir);
}
public void uploadTaobaoZipFile(ZipInputStream zipInput, String userId, String destDir)
throws Exception {
if (StringUtil.isBlank(userId)) {
uploadZip(zipInput, UNLOGIN_USER_PIC_PATH + SEP + destDir);
}
uploadZip(zipInput, userId + SEP + destDir);
}
/**
* 上传文件
* @param file
* @param destDir
* @return
*/
public String uploadFile(MultipartFile file, String destDir) {
String filePath = "";
if (file == null || StringUtil.isEmpty(file.getOriginalFilename())) {
return filePath;
}
String orgFileName = file.getOriginalFilename();
String exts = orgFileName.substring(orgFileName.lastIndexOf(".") + 1, orgFileName.length());
if (!ifExtendNamePermitted(exts)) {
//如果文件扩展名不在允许范围内
log.debug("文件扩展名不在允许范围内");
return filePath;
}
String newFileName = FileUploadUtil.createFileName(exts);
String saveDir = fileUploadDir + SEP + destDir + SEP + getSubFileDir();
try {
upfileToOss(file, saveDir, newFileName);
} catch (IOException e) {
log.error("FileUploadUtil.uploadFile", e);
}catch (Exception e){
log.error("Oss.uploadFile 异常", e);
}
filePath = fileUploadDir +destDir + SEP + getSubFileDir() + SEP + newFileName;
return filePath;
}
/**
* 上传文件
*
* @param file
* @param destDir
* @return
*/
public String uploadFileUnlimit(MultipartFile file, String destDir) {
String filePath = "";
if (file == null || StringUtil.isEmpty(file.getOriginalFilename())) {
return filePath;
}
String orgFileName = file.getOriginalFilename();
String exts = orgFileName.substring(orgFileName.lastIndexOf(".") + 1, orgFileName.length());
String newFileName = FileUploadUtil.createFileName(exts);
String saveDir = fileUploadDir + SEP + destDir + SEP + getSubFileDir();
try {
upfileToOss(file, saveDir, newFileName);
} catch (IOException e) {
log.error("FileUploadUtil.uploadFile", e);
}catch (Exception e){
log.error("Oss.uploadFile 异常", e);
}
filePath = fileUploadDir + SEP +destDir + SEP + getSubFileDir() + SEP + newFileName;
return filePath;
}
/**
* 上传文件
* @param file
* @param destDir
* @return
*/
public String uploadFileWithoutLimit(MultipartFile file, String destDir) {
String filePath = "";
if (file == null || StringUtil.isEmpty(file.getOriginalFilename())) {
return filePath;
}
String orgFileName = file.getOriginalFilename();
String exts = orgFileName.substring(orgFileName.lastIndexOf(".") + 1, orgFileName.length());
if (!ifExtendAllNamePermitted((exts))) { //如果文件扩展名不在允许范围内
log.debug("文件扩展名不在允许范围内");
return filePath;
}
String newFileName = FileUploadUtil.createFileName(exts);
String saveDir = fileUploadDir + SEP + destDir + SEP + getSubFileDir();
try {
upfileToOss(file, saveDir, newFileName);
} catch (IOException e) {
log.error("FileUploadUtil.uploadFile", e);
}catch (Exception e){
log.error("Oss.uploadFile 异常", e);
}
filePath = fileUploadDir + SEP +destDir + SEP + getSubFileDir() + SEP + newFileName;
return filePath;
}
/**
* 复制文件
* @param path
* @return
* @throws IOException
*/
public String copyFile(String path,String userId, String destDir) throws IOException{
String oldFilePath = fileUploadDir + SEP + path;
String newFilePath = fileUploadDir + SEP + userId + SEP + destDir + SEP + getSubFileDir();
String filePath = userId + SEP + destDir + SEP + getSubFileDir();
String exts = path.substring(path.lastIndexOf(".") + 1, path.length());
String newFileName = FileUploadUtil.createFileName(exts);
File newFile = new File(oldFilePath);
File file = new File(newFilePath);
if(!file.exists()){
file.mkdirs();
}
FileInputStream inputStream = new FileInputStream(newFile);
FileOutputStream outputStream = new FileOutputStream(new File(newFilePath+SEP+newFileName));
byte b[]=new byte[(int)newFile.length()];
inputStream.read(b);
outputStream.write(b);
outputStream.close();
return filePath+newFileName;
}
/**
* 上传图片
* @param file
* @param destDir
* @return
*/
public String uploadImg(MultipartFile file, String destDir,String imgName) {
String filePath = "";
if (file == null || StringUtil.isEmpty(file.getOriginalFilename())) {
return filePath;
}
String contentType = file.getContentType();
String exts = "jpg";
if (!ifExtendNamePermitted(exts)) {
//如果文件扩展名不在允许范围内
return filePath;
}
String newFileName = imgName +POINT + StringUtil.toLowerCase(exts);
String saveDir = fileUploadDir + SEP + destDir;
try {
upfileToOss(file, saveDir, newFileName);
} catch (IOException e) {
log.error("FileUploadUtil.uploadFile", e);
}catch (Exception e){
log.error("Oss.uploadFile 异常", e);
}
filePath = fileUploadDir + SEP +destDir + SEP + newFileName;
return filePath;
}
private static void saveFile(MultipartFile file, String destDir, String newFileName)
throws IOException {
if (!new File(destDir).exists()) {
new File(destDir).mkdirs();
}
file.transferTo(new File(destDir + SEP + newFileName));
}
private static void upfileToOss(MultipartFile multipartFile, String destDir, String newFileName)
throws IOException,Exception {
File file = MultipartFileToFile.multipartFileToFile(multipartFile);
OssService.uploadOSSfile(file,destDir + SEP + newFileName);
file.delete();
//file.transferTo(new File(destDir + SEP + newFileName));
}
public static synchronized String createFileName(String exts) {
Date date = new Date();
String fileName = getRandomString(8) + String.valueOf(date.getTime()) + POINT
+ StringUtil.toLowerCase(exts);
return fileName;
}
public synchronized String createFileNameOrg(String preName, String orgname, String backName) {
int i = orgname.lastIndexOf(".");
if (preName == null)
preName = "";
if (backName == null)
backName = "";
String fileName = "";
if (i != -1)
fileName = preName + orgname.substring(0, i) + backName
+ StringUtil.toLowerCase(orgname.substring(i));
else
fileName = preName + orgname.substring(0, i) + backName;
return fileName;
}
private static synchronized String getRandomString(int size) {// 随机字符串
char[] c = { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g',
'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm' };
Random random = new Random(System.currentTimeMillis()); // 初始化随机数产生器
StringBuffer sb = new StringBuffer();
for (int i = 0; i < size; i++) {
sb.append(c[Math.abs(random.nextInt(Integer.MAX_VALUE)) % c.length]);
}
double randtemp = Math.random();
if (randtemp < 0.1)
randtemp += 0.1;
if (randtemp == 1)
randtemp -= 0.001;
long temp = Math.round(randtemp * 1000);
return sb.toString() + temp;
}
public String getFileUploadDir() {
return fileUploadDir;
}
public void setFileUploadDir(String fileUploadDir) {
this.fileUploadDir = fileUploadDir;
}
public static String getSubFileDir() {
return DateUtil.getDateTime("yyyyMMdd", new Date());
}
/**
*
* @param file
* @param fileFileName
* @param uploadSubPath
* @return
* @throws Exception
*/
public synchronized String upload(File file, String fileFileName, String uploadSubPath)
throws FileNotFoundException,
IOException {
String fileName = null;
// the directory to upload to
String realPath = fileUploadDir + SEP + uploadSubPath + SEP;
// write the file to the file specified
File dirPath = new File(realPath);
// 如果没有,建立目录
if (!dirPath.exists()) {
dirPath.mkdirs();
}
// retrieve the file data
String fileType = StringUtil.toLowerCase(fileFileName.substring(StringUtil.lastIndexOf(
fileFileName, ".") + 1));
String randonFile = createFileName(fileType);
if (file.length() > 0) {
InputStream stream = new FileInputStream(file);
// write the file to the file specified
fileName = realPath + randonFile;
OutputStream bos = new FileOutputStream(fileName);
int bytesRead;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
stream.close();
}
return randonFile;
}
public synchronized void uploadZip(ZipInputStream in, String uploadSubPath)
throws FileNotFoundException,
IOException {
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
String realPath = fileUploadDir + SEP + uploadSubPath + SEP;
File dirPath = new File(realPath);
if (entry.isDirectory()) {
File create = new File(realPath);
create.mkdirs();
} else {
String entryName = entry.getName();
entryName = entryName.substring(entryName.lastIndexOf("/") + 1, entryName.length());
entryName = entryName.substring(0, entryName.lastIndexOf("."));
File create = new File(dirPath, entryName + ".jpg");
File parent = create.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(create);
IOUtils.copy(in, fos);
} finally {
if (fos != null) {
fos.close();
}
}
}
}
}
public String deleteFile(String path){
String result = "false";
File file = new File(fileUploadDir+path);
if(file.isFile() && file.exists()){
file.delete();
result = "true";
}
return result;
}
//下载文件
public static void downLoadFile(String filePath, String filename, HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
OutputStream os = null;
FileInputStream fis = null;
try {
if (!(new File(filePath)).exists()) {
return;
}
os = response.getOutputStream();
response
.setHeader("content-disposition", "attachment;filename=" + toUtf8String(filename));
response.setContentType("application/vnd.rn-realmedia-vbr");//此项内容随文件类型而异
byte temp[] = new byte[1000];
fis = new FileInputStream(filePath);
int n = 0;
while ((n = fis.read(temp)) != -1) {
os.write(temp, 0, n);
}
}catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null)
os.close();
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String toUtf8String(String src) throws UnsupportedEncodingException {
return URLEncoder.encode(src, "UTF-8");
}
public String excelImport(MultipartFile file){
MultipartFile[] files = new MultipartFile[1];
files[0] = file;
return null;
}
/**
* 上传文件,验证不同类型文件
* @param file
* @param destDir
* @return
*/
public String uploadFileType(MultipartFile file, String destDir,String type) {
String filePath = "";
if (file == null || StringUtil.isEmpty(file.getOriginalFilename())) {
return filePath;
}
String orgFileName = file.getOriginalFilename();
String exts = orgFileName.substring(orgFileName.lastIndexOf(".") + 1, orgFileName.length());
if (!ifExtendNamePermitted(exts,type)) {
//如果文件扩展名不在允许范围内
log.debug("文件扩展名不在允许范围内");
return filePath;
}
String newFileName = FileUploadUtil.createFileName(exts);
String saveDir = fileUploadDir + SEP + destDir + SEP + getSubFileDir();
try {
saveFile(file, saveDir, newFileName);
} catch (IOException e) {
log.error("文件上传失败", e);
}
filePath = destDir + SEP + getSubFileDir() + SEP + newFileName;
return filePath;
}
/**
* 导出准备
* @param response
* @param fileName
* @throws UnsupportedEncodingException
*/
public static void prepareResponseExport(HttpServletResponse response, String fileName)
throws UnsupportedEncodingException {
// 做一些准备工作
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
String fn = new String((fileName + ".xls").getBytes("GBK"), "ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fn + "\"");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setDateHeader("Expires", (System.currentTimeMillis() + 1000));
}
public Properties readProperties(){
Properties prop = new Properties();
try{
//读取属性文件a.properties
InputStream in = this.getClass().getResourceAsStream("/server.properties");
prop.load(in); ///加载属性列表
Iterator<String> it=prop.stringPropertyNames().iterator();
while(it.hasNext()){
String key=it.next();
//logger.info(key+":"+prop.getProperty(key));
}
in.close();
}catch(Exception e){
log.error("==readProperties==",e);
}
return prop;
}
// /**
// * 得到普通字体格式
// * @param workbook2003
// * @return
// */
// public static HSSFCellStyle getNomalCellStyle(HSSFWorkbook workbook2003) {
// HSSFCellStyle style = workbook2003.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);//下边框
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
// style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
// HSSFFont font = workbook2003.createFont();
// font.setFontHeightInPoints((short) 10);
// font.setFontName("宋体");
// style.setFont(font);
// return style;
// }
//
// /**
// * 得到加粗字体格式
// * @param workbook2003
// * @return
// */
// public static HSSFCellStyle getBoldCellStyle(HSSFWorkbook workbook2003) {
// HSSFCellStyle styleBold = getNomalCellStyle(workbook2003);
// HSSFFont font = workbook2003.createFont();
// font.setFontHeightInPoints((short) 10);
// font.setFontName("宋体");
// font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗
// styleBold.setFont(font);
// return styleBold;
// }
// /**
// * 填充单元格.
// * @param row
// * @param cellnum
// * @param style
// * @param value
// */
// public static void fillCell(HSSFRow row, int cellnum, HSSFCellStyle style, String value) {
// HSSFCell cell = row.createCell(cellnum);
// cell.setCellStyle(style);
// cell.setCellValue(value); //设置Excel工作表的值
// }
}