package net.onerock.topic.utils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author LHW
* @Description 操作文件工具类
* @Date 2018年6月8日 上午11:42:44
* @Version v1.0
*/
public class OperationFileUtil {
private static OperationFileUtil instance;
private OperationFileUtil() {
super();
}
public static OperationFileUtil getInstance() {
if (instance == null) {
synchronized (OperationFileUtil.class){
instance = new OperationFileUtil();
}
}
return instance;
}
/**
* TODO:文件下载
*
* @param request
* @param response
* @param downFileName 下载时候的文件的名字("下载.txt")
* @param fileName 文件的名字 ("demo.txt")
* @param filePath 文件的路径 ("/opt/file")
* @throws RuntimeException
*/
/**
*
* @param request
* @param response
* @param downFileName TODO:文件下载后的名字
* @param fileName TODO:文件的UUID
* @param filePath TODO:文件的路径
* @throws Exception
*/
public void httpDownLoad(HttpServletRequest request, HttpServletResponse response,String downFileName, String fileName, String filePath) throws Exception {
File file = new File(filePath + File.separator + fileName);
if (!file.exists()) {
throw new RuntimeException("文件不存在");
}
InputStream inStream = new FileInputStream(filePath + File.separator + fileName);// 文件的存放路径
// 设置输出的格式
response.reset();
response.setContentType("application/octet-stream");
/*
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
//ie
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
//其它浏览器
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
*/
downFileName = URLEncoder.encode(downFileName, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + downFileName);
// 循环取出流中的数据
byte[] b = new byte[100];
int len;
while ((len = inStream.read(b)) > 0) {
response.getOutputStream().write(b, 0, len);
}
inStream.close();
}
/**
* 文件上传OFD
*
* @param path
* @param file
* @return
*/
public Map<String, Object> uploadOFD(String path, MultipartFile file) {
Map<String, Object> map = new HashMap<String, Object>();
SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyyMMddHHmmss");
try {
String fileName = file.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
String uuidName = Identities.uuid() + dateformat1.format(new Date()) + "." + prefix;
File dir = new File(path, uuidName);
if (!dir.exists()) {
dir.mkdirs();
}
// MultipartFile自带的解析方法
file.transferTo(dir);
String filePath = path + File.separator + uuidName;
File f = new File(filePath);
if (f.exists()) {
map.put("status", true);
map.put("name", fileName);
map.put("path", path);
map.put("uuidname", uuidName);
} else {
map.put("status", false);
}
} catch (Exception e) {
System.out.println("**********************OFD文件上传失败!**********************");
e.printStackTrace();
}
return map;
}
//返回值 :list对象,包含内容依次为
//1.上传是否成功(0代表文件上传失败,1代表文件上传成功)
//2.文件名
//3.已上传文件大小
public List<String> uploadMethod(HttpServletRequest request,
HttpServletResponse response,
String tempFilePath,
String realFilePath,
String realFileName) throws Exception {
List<String> ret = new ArrayList();
try {
long now = System.currentTimeMillis();
//根据系统时间生成上传够保存的文件名
String prefix = String.valueOf(now);
//设置长传文件的最大值:200MB
final long MAX_SIZE = 200 * 1024 * 1024;
response.setContentType("text/html");
//字符编码为UTF-8
response.setCharacterEncoding("UTF-8");
//实例化一个硬盘文件工厂,用来配置文件组建ServletFileUpload
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置长传文件时用于临时存放文件的内存大小,这里是4K,多余的部分将临时存在硬盘
factory.setSizeThreshold(4096);
//设置存放临时文件的目录,web根目录下的UploadTemp目录
//factory.setRepository(new File(request.getRealPath("/")+ "UploadTemp"));
System.out.println("写入文件:" + tempFilePath);
factory.setRepository(new File(tempFilePath));
/**
* 用以上工厂实例化长传组件
*/
ServletFileUpload sfu = new ServletFileUpload(factory);
//设置最大上传尺寸
sfu.setSizeMax(MAX_SIZE);
PrintWriter out = response.getWriter();
//从request得到 所有 上传域的列表
List<FileItem> fileList = null;
try {
fileList = sfu.parseRequest(request);
} catch (Exception e) {
System.out.println("=========================================");
e.printStackTrace();
System.out.println("=========================================");
try {
int bytesum = 0;
int byteread = 0;
String tempName = "temp.txt";//factory.getTempFileName();
// MkDirData.getInstance().createMkdir(tempFilePath);
String oldPath = tempFilePath + "/" + tempName;
//String oldPath = request.getRealPath("/") + "UploadTemp"+ "/" + tempFileName;
System.out.println("创建文件目录:" + realFilePath);
// MkDirData.getInstance().createMkdir(realFilePath);
String newPath = realFilePath + "/" + tempName;
//String newPath = request.getRealPath("/") + "/UploadFile/"+ tempFileName;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
System.out.println("写入新文件:" + newPath);
byte[] buffer = new byte[4444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
//System.out.println("文件大小="+oldfile.length());
ret.add("0");
ret.add(tempName);
ret.add(oldfile.length() + "");
return ret;
}
} catch (Exception ex) {
System.out.println("复制temp文件操作出错");
System.out.println("=========================================");
ex.printStackTrace();
System.out.println("=========================================");
ret.add("0");
ret.add(null);
ret.add(null);
return ret;
}
System.out.println("e.getMessage=" + e.getMessage());
}
//得到所有上传的文件
Iterator fileItr = null;
if (fileList != null) {
fileItr = fileList.iterator();
}
long size = 0;
// 循环处理所有文件
while (fileItr != null && fileItr.hasNext()) {
FileItem fileItem = null;
String path = "";
// 获取当前文件
// 获取当前文件
Object obj = fileItr.next();
if (obj != null && obj instanceof FileItem) {
fileItem = (FileItem) obj;
} else {
continue;
}
// 忽略简单form字段 而不是 上传域的文件域(<input type="text" />等)
if (fileItem == null || fileItem.isFormField()) {
continue;
}
// 获取文件的完整路径
path = fileItem.getName();
//System.out.println("path="+path);
// 获取文件大小
size = fileItem.getSize();
//System.out.println("size="+size);
// 得到去除路径的文件名
String realName = path.substring(path.lastIndexOf("\\") + 1);
//System.out.println("realName="+realName);
// 得到文件的拓展名(无拓展名时将得到全名)
String extName = realName
.substring(realName.lastIndexOf(".") + 1);
// 保存的最终文件完整路径,保存在web根目录下的UploadFile目录下
//String finalName = request.getRealPath("/") + "/UploadFile/"+ prefix + "." + extName;
String finalName = realFilePath + "/" + realFileName;
//System.out.println("finalName="+finalName);
try {
// 保存文件
fileItem.write(new File(finalName));
} catch (Exception e) {
//System.out.println(e.getMessage());
}
}
ret.add("1");
ret.add(realFileName);
ret.add(size + "");
return ret;
} catch (Exception ex) {
ex.printStackTrace();
ret.add("0");
ret.add("");
ret.add("0");
return ret;
}
}
}