package com.gootrip.util;

import java.io.File;
import java.util.*;
import org.apache.commons.fileupload.*;
import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;
import java.io.IOException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import java.util.regex.Matcher; public class FileUploadUtil { //当上传文件超过限制时设定的临时文件位置,注意是绝对路径
private String tempPath = null; //文件上传目标目录,注意是绝对路径
private String dstPath = null; //新文件名称,不设置时默认为原文件名
private String newFileName = null;
//获取的上传请求
private HttpServletRequest fileuploadReq = null; //设置最多只允许在内存中存储的数据,单位:字节,这个参数不要设置太大
private int sizeThreshold = 4096; //设置允许用户上传文件大小,单位:字节
//共10M
private long sizeMax = 10485760; //图片文件序号
private int picSeqNo = 1; private boolean isSmallPic = false; public FileUploadUtil(){
} public FileUploadUtil(String tempPath, String destinationPath){
this.tempPath = tempPath;
this.dstPath = destinationPath;
} public FileUploadUtil(String tempPath, String destinationPath, HttpServletRequest fileuploadRequest){
this.tempPath = tempPath;
this.dstPath = destinationPath;
this.fileuploadReq = fileuploadRequest;
} /** 文件上载
* @return true —— success; false —— fail.
*/
public boolean Upload(){
DiskFileItemFactory factory = new DiskFileItemFactory(); try { //如果没有上传目的目录,则创建它
FileUtil.makeDirectory(dstPath+"/ddd");
/*if (!FileUtil.makeDirectory(dstPath+"/ddd")) {
throw new IOException("Create destination Directory Error.");
}*/
//如果没有临时目录,则创建它
FileUtil.makeDirectory(tempPath+"/ddd");
/*if (!FileUtil.makeDirectory(tempPath+"/ddd")) {
throw new IOException("Create Temp Directory Error.");
}*/ //上传项目只要足够小,就应该保留在内存里。
//较大的项目应该被写在硬盘的临时文件上。
//非常大的上传请求应该避免。
//限制项目在内存中所占的空间,限制最大的上传请求,并且设定临时文件的位置。 //设置最多只允许在内存中存储的数据,单位:字节
factory.setSizeThreshold(sizeThreshold);
// the location for saving data that is larger than getSizeThreshold()
factory.setRepository(new File(tempPath)); ServletFileUpload upload = new ServletFileUpload(factory);
//设置允许用户上传文件大小,单位:字节
upload.setSizeMax(sizeMax); List fileItems = upload.parseRequest(fileuploadReq);
// assume we know there are two files. The first file is a small
// text file, the second is unknown and is written to a file on
// the server
Iterator iter = fileItems.iterator(); // 正则匹配,过滤路径取文件名
String regExp = ".+\\\\(.+)$"; // 过滤掉的文件类型
String[] errorType = {".exe", ".com", ".cgi", ".asp", ".php", ".jsp"};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
System.out.println("++00++====="+newFileName);
FileItem item = (FileItem) iter.next();
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
System.out.println("++++====="+name);
long size = item.getSize();
//有多个文件域时,只上传有文件的
if ((name == null || name.equals("")) && size == 0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result) {
for (int temp = 0; temp < errorType.length; temp++) {
if (m.group(1).endsWith(errorType[temp])) {
throw new IOException(name + ": Wrong File Type");
}
}
String ext = "."+FileUtil.getTypePart(name);
try {
//保存上传的文件到指定的目录
//在下文中上传文件至数据库时,将对这里改写
//没有指定新文件名时以原文件名来命名
if (newFileName == null || newFileName.trim().equals(""))
{
item.write(new File(dstPath +"/"+ m.group(1)));
}
else
{
String uploadfilename = "";
if (isSmallPic)
{
uploadfilename = dstPath +"/"+ newFileName+"_"+picSeqNo+"_small"+ext;
}
else
{
uploadfilename = dstPath +"/"+ newFileName+"_"+picSeqNo+ext;
}
//生成所有未生成的目录
System.out.println("++++====="+uploadfilename);
FileUtil.makeDirectory(uploadfilename);
//item.write(new File(dstPath +"/"+ newFileName));
item.write(new File(uploadfilename));
}
picSeqNo++;
//out.print(name + "&nbsp;&nbsp;" + size + "<br>");
} catch (Exception e) {
//out.println(e);
throw new IOException(e.getMessage());
}
} else {
throw new IOException("fail to upload");
}
}
}
} catch (IOException e) {
System.out.println(e);
} catch (FileUploadException e) {
System.out.println(e);
}
return true;
} /**从路径中获取单独文件名
* @author
*
* TODO 要更改此生成的类型注释的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
public String GetFileName(String filepath)
{
String returnstr = "*.*";
int length = filepath.trim().length(); filepath = filepath.replace('\\', '/');
if(length >0)
{
int i = filepath.lastIndexOf("/");
if (i >= 0)
{
filepath = filepath.substring(i + 1);
returnstr = filepath;
}
}
return returnstr;
}
/**
* 设置临时存贮目录
*/
public void setTmpPath(String tmppath)
{
this.tempPath = tmppath;
}
/**
* 设置目标目录
*/
public void setDstPath(String dstpath) {
this.dstPath = dstpath;
}
/**
* 设置最大上传文件字节数,不设置时默认10M
*/
public void setFileMaxSize(long maxsize) {
this.sizeMax = maxsize;
}
/**
* 设置Http 请求参数,通过这个能数来获取文件信息
*/
public void setHttpReq(HttpServletRequest httpreq) {
this.fileuploadReq = httpreq;
}
/**
* 设置Http 请求参数,通过这个能数来获取文件信息
*/
public void setNewFileName(String filename) {
this.newFileName = filename;
} /**
* 设置此上传文件是否是缩略图文件,这个参数主要用于缩略图命名
*/
public void setIsSmalPic(boolean isSmallPic) {
this.isSmallPic = isSmallPic;
} /**
* 设置Http 请求参数,通过这个能数来获取文件信息
*/
public void setPicSeqNo(int seqNo) {
this.picSeqNo = seqNo;
} }

Java-FileUploadUtil工具类的更多相关文章

  1. Java Properties工具类详解

    1.Java Properties工具类位于java.util.Properties,该工具类的使用极其简单方便.首先该类是继承自 Hashtable<Object,Object> 这就奠 ...

  2. Java json工具类,jackson工具类,ObjectMapper工具类

    Java json工具类,jackson工具类,ObjectMapper工具类 >>>>>>>>>>>>>>> ...

  3. Java日期工具类,Java时间工具类,Java时间格式化

    Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...

  4. Java并发工具类 - CountDownLatch

    Java并发工具类 - CountDownLatch 1.简介 CountDownLatch是Java1.5之后引入的Java并发工具类,放在java.util.concurrent包下面 http: ...

  5. MinerUtil.java 爬虫工具类

    MinerUtil.java 爬虫工具类 package com.iteye.injavawetrust.miner; import java.io.File; import java.io.File ...

  6. MinerDB.java 数据库工具类

    MinerDB.java 数据库工具类 package com.iteye.injavawetrust.miner; import java.sql.Connection; import java.s ...

  7. 小记Java时间工具类

    小记Java时间工具类 废话不多说,这里主要记录以下几个工具 两个时间只差(Data) 获取时间的格式 格式化时间 返回String 两个时间只差(String) 获取两个时间之间的日期.月份.年份 ...

  8. Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie

    Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie >>>>>>>>>>>>& ...

  9. UrlUtils工具类,Java URL工具类,Java URL链接工具类

    UrlUtils工具类,Java URL工具类,Java URL链接工具类 >>>>>>>>>>>>>>>&g ...

  10. java日期工具类DateUtil-续一

    上篇文章中,我为大家分享了下DateUtil第一版源码,但就如同文章中所说,我发现了还存在不完善的地方,所以我又做了优化和扩展. 更新日志: 1.修正当字符串日期风格为MM-dd或yyyy-MM时,若 ...

随机推荐

  1. 在docker容器下安装airflow

    本人的环境是基于centos7下来安装的 一.安装docker  下载docker安装包,下载地址:https://download.docker.com/linux/static/stable/x8 ...

  2. Win7/Win2008下IIS配置Asp站点启用父路径的设置方法

    iis日志错误如下: 修改路径文件权限问题依旧. 解决方式:

  3. SQL SERVER DATEPART函数

    定义: DATEPART函数返回指定日期的指定部分. 语法: DATEPART(datepart,date) 参数: ①datepart 参数可以是下列的值: datepart 缩写 年(Year) ...

  4. Codeforces 1148E Earth Wind and Fire

    分析 必要条件: ① $\sum_{i=1}^{n} s_i = \sum_{i=1}^{n} t_i$ 预处理: 将 $s, t$ 从小到大排序. 尝试一 首尾匹配.例子 s = 2, 2, 4, ...

  5. spring-boot 使用servlet2.5(四)

    环境 jdk 6 tomcat 6.0.53 sts 4.4.2 maven 3.2.5 背景 由于环境限制,还在使用 servlet 2.5,所以需要将 spring boot 进行配置,支持 se ...

  6. 函数try{}

    语法 函数try块是一种函数体的替代语法形式,是函数定义的一部分 try构造函数初始化器 复合语句 处理块序列 (1)构造函数初始化器 - 成员初始化器列表,只在构造函数允许 (2)复合语句 - 花括 ...

  7. spark内核篇-任务调度机制

    在生产环境中,spark 部署方式一般都是 yarn-cluster 模式,本文针对该模式进行讲解,当然大体思路也适用于其他模式 基础概念 一个 spark 应用包含 job.stage.task 三 ...

  8. Codeforces 1240A. Save the Nature

    传送门 显然可以二分答案 如果知道卖的票数,那么就能算出有多少 $a$ 倍数但不是 $b$ 倍数的位置,多少 $b$ 倍数但不是 $a$ 倍数的位置,多少既是 $a$ 又是 $b$ 倍数的位置 然后贪 ...

  9. Vasya and Endless Credits CodeForces - 1107F (二分图完美匹配)

    大意: n中贷款, 每种只能买一次, 第$i$种给$a_i$元, 要还款$k_i$个月, 每个月底还$b_i$元. 每个月可以在月初申请一种贷. 求某一时刻能得到的最大钱数.

  10. C#中word文档转html

    var path = Request.Url.Host + ":" + Request.Url.Port + list[i].AnnexPath; //html保存路径 strin ...