Java-FileUploadUtil工具类
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 + " " + 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工具类的更多相关文章
- Java Properties工具类详解
1.Java Properties工具类位于java.util.Properties,该工具类的使用极其简单方便.首先该类是继承自 Hashtable<Object,Object> 这就奠 ...
- Java json工具类,jackson工具类,ObjectMapper工具类
Java json工具类,jackson工具类,ObjectMapper工具类 >>>>>>>>>>>>>>> ...
- Java日期工具类,Java时间工具类,Java时间格式化
Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...
- Java并发工具类 - CountDownLatch
Java并发工具类 - CountDownLatch 1.简介 CountDownLatch是Java1.5之后引入的Java并发工具类,放在java.util.concurrent包下面 http: ...
- MinerUtil.java 爬虫工具类
MinerUtil.java 爬虫工具类 package com.iteye.injavawetrust.miner; import java.io.File; import java.io.File ...
- MinerDB.java 数据库工具类
MinerDB.java 数据库工具类 package com.iteye.injavawetrust.miner; import java.sql.Connection; import java.s ...
- 小记Java时间工具类
小记Java时间工具类 废话不多说,这里主要记录以下几个工具 两个时间只差(Data) 获取时间的格式 格式化时间 返回String 两个时间只差(String) 获取两个时间之间的日期.月份.年份 ...
- Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie
Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie >>>>>>>>>>>>& ...
- UrlUtils工具类,Java URL工具类,Java URL链接工具类
UrlUtils工具类,Java URL工具类,Java URL链接工具类 >>>>>>>>>>>>>>>&g ...
- java日期工具类DateUtil-续一
上篇文章中,我为大家分享了下DateUtil第一版源码,但就如同文章中所说,我发现了还存在不完善的地方,所以我又做了优化和扩展. 更新日志: 1.修正当字符串日期风格为MM-dd或yyyy-MM时,若 ...
随机推荐
- 15.sqoop数据从mysql里面导入到HDFS里面
表数据 在mysql中有一个库userdb中三个表:emp, emp_add和emp_contact 表emp id name deg salary dept 1201 gopal manager 5 ...
- Springboot使用launch.script打包后解压缩
今天拿到一个SpringBoot的jar需要反编译看一下.直接用工具试了下提示报错. 于是用文本工具打开看了下,发现此JAR包在打包时候引入了启动脚本.如下图: 为了反编译,可以直接将所有启动脚本相关 ...
- Design HashMap
Design a HashMap without using any built-in hash table libraries. To be specific, your design should ...
- Docker CE 下载方式
1. 找到一个网址挺好的 https://download.docker.com/linux/ubuntu/dists/xenial/pool/stable/arm64/ mark 一下 以后用.
- Servlet中获取POST请求的参数
在servlet.filter等中获取POST请求的参数 form表单形式提交post方式,可以直接从 request 的 getParameterMap 方法中获取到参数 JSON形式提交post方 ...
- vue 评论 computed watch 分隔符 局部组件 全局组件 子传父消息|父传子消息
评论案例 splice: (start 几位,替换(新增)内容) splice(0,0,内容)在头部插入内容 splice(0,1) 把索引为0的往后删除1位 splice(0,1,内容)把索引为0 ...
- 【计数】Simple Addition Expression
[来源] 2008年哈尔滨区域赛 [题目链接]: http://acm.hdu.edu.cn/showproblem.php?pid=2451 [参考博客]: HDU 2451 Simple Addi ...
- Centos7.3安装Oracle11.2.0.3
1.创建用户用户组 [root@smallcloud ~]# groupadd oinstall [root@smallcloud ~]# groupadd dba [root@smallcloud ...
- 怎样在 Vue 里面使用自定义事件将子组件的数据传回给父组件?
首先, Vue 里面的组件之间的数据流动是 单向 的, 数据可以从父组件传递给子组件, 但不能从子组件传递给父组件, 因为组件和组件之间是 隔离 的. 就像两个嵌套的 黑盒子 . 能通过 props ...
- Scala学习十二——高阶函数
一.本章要点 在Scala中函数是”头等公民“(可以作为参数,返回值,赋值给其他); 可以创建匿名函数,通常还会交给其他函数; 函数参数可以给出需要稍后执行的行为; 许多集合方法都接受函数参数,将函数 ...