package com.ad.web.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import richinfo.rmapi.common.ReturnCode;
import richinfo.tools.Tools;
import cn.richinfo.cmail.common.config.PropertiesUtil;
import com.ad.web.common.CommonConst;
import com.ad.web.servlet.common.ImpProcess;
import com.ad.web.servlet.common.Informations;
/**
* 说明:个人通讯录人员导入入口类
* @author zxkj
*
*/
public class FileUploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(FileUploadServlet.class);
final long MAX_SIZE = 1 * 1024 * 1024;// 设置上传文件最大为 1M
final String[] allowtype = new String[] { "csv", "vcf" }; // 允许上传的文件格式的列表
public FileUploadServlet()
{
super();
}
public void destroy()
{
super.destroy();
}
@SuppressWarnings( { "deprecation", "unchecked" })
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String rmkey = "";
String maindomain="";
Cookie [] cookies=request.getCookies();
if(cookies!=null)
{
for(int i=0;i<cookies.length;i++)
{
String cookieName = cookies[i].getName();
if("maindomain".equals(cookieName))
{
maindomain=cookies[i].getValue();
}
if ("RMKEY".equals(cookieName)) {
rmkey = cookies[i].getValue();
}
}
}
int imp_size=1;
String max=PropertiesUtil.getProperty(CommonConst.IMP_SIZE);
if(max!=null && !"".equals(max))
{
imp_size=Integer.parseInt(max);
}
String sid =request.getParameter("sid");
String rp = request.getParameter("rp");
String retr ="";
String fc=request.getParameter("func");
if(fc!=null && !"".equals(fc))
{
fc=StringEscapeUtils.escapeHtml(fc);
retr=URLEncoder.encode(fc, "UTF-8");
}
String path = null;
FileItem fileItem = null;
FileItem fileUploadItem = null;
File file=null;
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
dfif.setSizeThreshold(4 * 1024);
if (!(new File(request.getRealPath("/") + "uploadtemp").isDirectory()))
{
new File(request.getRealPath("/") + "uploadtemp").mkdir();
}
// 设置存放临时文件的目录,web根目录下的uploadtemp目录
dfif.setRepository(new File(request.getRealPath("/") + "uploadtemp"));
// 用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(dfif);
sfu.setHeaderEncoding("utf-8");
// 设置最大上传尺寸
PrintWriter out = response.getWriter();
List fileList = null;
try
{
fileList = sfu.parseRequest(request);
// 没有文件上传
if (fileList == null || fileList.size() == 0)
{
Informations.resMessage(out, "请选择上传文件", retr,maindomain);
return;
}
// 得到所有上传的文件
Iterator fileItr = fileList.iterator();
// 循环处理所有文件
while (fileItr.hasNext())
{
long size = 0;
// 得到当前文件
fileItem = (FileItem) fileItr.next();
if (fileItem.isFormField())
{
String name = fileItem.getFieldName();
String v = fileItem.getString();
if ("sid".equals(name))
{
sid = v;
}
else if ("func".equals(name))
{
retr = v;
}
else if ("rp".equals(name))
{
rp = v;
}
}
else
{
fileUploadItem=fileItem;
// 得到文件的完整路径
path = fileItem.getName();
// 得到文件的大小
size = fileItem.getSize();
if ("".equals(path) || size == 0)
{
Informations.resMessage(out, "请选择上传文件或上传文件为空", retr,maindomain);
return;
}
if(size>(1024*1024*imp_size))
{
Informations.resMessage(out, "文件大小超过"+imp_size+"M", retr,maindomain);
return;
}
}
}
// 得到去除路径的文件名
String t_name = path.substring(path.lastIndexOf("\\") + 1);
// 得到文件的扩展名(无扩展名时将得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
// 拒绝接受规定文件格式之外的文件类型
int allowFlag = 0;
int allowedExtCount = allowtype.length;
for (; allowFlag < allowedExtCount; allowFlag++)
{
if (allowtype[allowFlag].equals(t_ext))
{
break;
}
}
if (allowFlag == allowedExtCount)
{
String message = "";
for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
{
message += "*." + allowtype[allowFlag] + " ";
}
Informations.resMessage(out, "请选择:" + message + "类型文件", retr,maindomain);
return;
}
long now = System.currentTimeMillis();
// 根据系统时间生成上传后保存的文件名
String prefix = String.valueOf(now);
// 保存的最终文件完整路径,保存在web根目录下的upload目录下
if (!(new File(request.getRealPath("/") + "upload").isDirectory()))
{
new File(request.getRealPath("/") + "upload").mkdir();
}
// 现在文件名
path = request.getRealPath("/") + "upload/" + prefix + "." + t_ext;
// 保存文件
fileUploadItem.write(new File(path));
// 开始处理上传文件,进行数据入库操作
String msg = ImpProcess.importUsers(path, sid, rp, t_ext,rmkey);
// 操作完成删除文件
file = new File(path);
JSONObject jsonObject = JSONObject.fromObject(msg);
String code = jsonObject.get("code").toString();
if (Tools.isNotEmpty(code) && code.trim().equals(ReturnCode.S_OK))
{
Informations.serviceMessage(out, msg, retr,maindomain);
return;
}
else
{
Informations.serviceMessage(out, msg, retr,maindomain);
return;
}
}
catch (FileUploadException e)
{
Informations.resMessage(out, "导入失败", retr,maindomain);
log.error("sid="+sid +" | result=failure",e);
return;
}
catch (Exception e)
{
Informations.resMessage(out, "导入失败", retr,maindomain);
log.error("sid="+sid+" | result=failure",e);
}
finally
{
if (out != null)
{
out.close();
}
if(file!=null)
{
if (file.exists())
{
file.delete();
}
}
}
}
}
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import richinfo.rmapi.common.ReturnCode;
import richinfo.tools.Tools;
import cn.richinfo.cmail.common.config.PropertiesUtil;
import com.ad.web.common.CommonConst;
import com.ad.web.servlet.common.ImpProcess;
import com.ad.web.servlet.common.Informations;
/**
* 说明:个人通讯录人员导入入口类
* @author zxkj
*
*/
public class FileUploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(FileUploadServlet.class);
final long MAX_SIZE = 1 * 1024 * 1024;// 设置上传文件最大为 1M
final String[] allowtype = new String[] { "csv", "vcf" }; // 允许上传的文件格式的列表
public FileUploadServlet()
{
super();
}
public void destroy()
{
super.destroy();
}
@SuppressWarnings( { "deprecation", "unchecked" })
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String rmkey = "";
String maindomain="";
Cookie [] cookies=request.getCookies();
if(cookies!=null)
{
for(int i=0;i<cookies.length;i++)
{
String cookieName = cookies[i].getName();
if("maindomain".equals(cookieName))
{
maindomain=cookies[i].getValue();
}
if ("RMKEY".equals(cookieName)) {
rmkey = cookies[i].getValue();
}
}
}
int imp_size=1;
String max=PropertiesUtil.getProperty(CommonConst.IMP_SIZE);
if(max!=null && !"".equals(max))
{
imp_size=Integer.parseInt(max);
}
String sid =request.getParameter("sid");
String rp = request.getParameter("rp");
String retr ="";
String fc=request.getParameter("func");
if(fc!=null && !"".equals(fc))
{
fc=StringEscapeUtils.escapeHtml(fc);
retr=URLEncoder.encode(fc, "UTF-8");
}
String path = null;
FileItem fileItem = null;
FileItem fileUploadItem = null;
File file=null;
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
dfif.setSizeThreshold(4 * 1024);
if (!(new File(request.getRealPath("/") + "uploadtemp").isDirectory()))
{
new File(request.getRealPath("/") + "uploadtemp").mkdir();
}
// 设置存放临时文件的目录,web根目录下的uploadtemp目录
dfif.setRepository(new File(request.getRealPath("/") + "uploadtemp"));
// 用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(dfif);
sfu.setHeaderEncoding("utf-8");
// 设置最大上传尺寸
PrintWriter out = response.getWriter();
List fileList = null;
try
{
fileList = sfu.parseRequest(request);
// 没有文件上传
if (fileList == null || fileList.size() == 0)
{
Informations.resMessage(out, "请选择上传文件", retr,maindomain);
return;
}
// 得到所有上传的文件
Iterator fileItr = fileList.iterator();
// 循环处理所有文件
while (fileItr.hasNext())
{
long size = 0;
// 得到当前文件
fileItem = (FileItem) fileItr.next();
if (fileItem.isFormField())
{
String name = fileItem.getFieldName();
String v = fileItem.getString();
if ("sid".equals(name))
{
sid = v;
}
else if ("func".equals(name))
{
retr = v;
}
else if ("rp".equals(name))
{
rp = v;
}
}
else
{
fileUploadItem=fileItem;
// 得到文件的完整路径
path = fileItem.getName();
// 得到文件的大小
size = fileItem.getSize();
if ("".equals(path) || size == 0)
{
Informations.resMessage(out, "请选择上传文件或上传文件为空", retr,maindomain);
return;
}
if(size>(1024*1024*imp_size))
{
Informations.resMessage(out, "文件大小超过"+imp_size+"M", retr,maindomain);
return;
}
}
}
// 得到去除路径的文件名
String t_name = path.substring(path.lastIndexOf("\\") + 1);
// 得到文件的扩展名(无扩展名时将得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
// 拒绝接受规定文件格式之外的文件类型
int allowFlag = 0;
int allowedExtCount = allowtype.length;
for (; allowFlag < allowedExtCount; allowFlag++)
{
if (allowtype[allowFlag].equals(t_ext))
{
break;
}
}
if (allowFlag == allowedExtCount)
{
String message = "";
for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
{
message += "*." + allowtype[allowFlag] + " ";
}
Informations.resMessage(out, "请选择:" + message + "类型文件", retr,maindomain);
return;
}
long now = System.currentTimeMillis();
// 根据系统时间生成上传后保存的文件名
String prefix = String.valueOf(now);
// 保存的最终文件完整路径,保存在web根目录下的upload目录下
if (!(new File(request.getRealPath("/") + "upload").isDirectory()))
{
new File(request.getRealPath("/") + "upload").mkdir();
}
// 现在文件名
path = request.getRealPath("/") + "upload/" + prefix + "." + t_ext;
// 保存文件
fileUploadItem.write(new File(path));
// 开始处理上传文件,进行数据入库操作
String msg = ImpProcess.importUsers(path, sid, rp, t_ext,rmkey);
// 操作完成删除文件
file = new File(path);
JSONObject jsonObject = JSONObject.fromObject(msg);
String code = jsonObject.get("code").toString();
if (Tools.isNotEmpty(code) && code.trim().equals(ReturnCode.S_OK))
{
Informations.serviceMessage(out, msg, retr,maindomain);
return;
}
else
{
Informations.serviceMessage(out, msg, retr,maindomain);
return;
}
}
catch (FileUploadException e)
{
Informations.resMessage(out, "导入失败", retr,maindomain);
log.error("sid="+sid +" | result=failure",e);
return;
}
catch (Exception e)
{
Informations.resMessage(out, "导入失败", retr,maindomain);
log.error("sid="+sid+" | result=failure",e);
}
finally
{
if (out != null)
{
out.close();
}
if(file!=null)
{
if (file.exists())
{
file.delete();
}
}
}
}
}