下载文件
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doPost(request, response);
//System.out.println("下载");
response.setContentType("application/x-download");
PropertyBean propertyBeanURL = new PropertyBean();
propertyBeanURL.setPropertiesFile("mail.properties");
propertyBeanURL.init();
String tempUrl = propertyBeanURL.get("temp");
String filePath = tempUrl+ File.separatorChar+ "CrmUpload" +File.separatorChar;
String filedownload = filePath + "tcsl_mobile.xls";
//String filePath = getPropertyBean("ticketFilePath"); //"E:\\CrmUpload\\";
//String filedownload = filePath + getPropertyBean("ticketTemplatesFile"); //filePath + "mobile.xls";//文件名
String filedisplay = "非会员电话号码模版.xls";//下载文件时显示的文件保存名称
String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
OutputStream outp = null;
FileInputStream in = null;
try
{
outp = response.getOutputStream();
File truefile=new File(filedownload);
in = new FileInputStream(truefile);
byte[] b = new byte[1024];
int i = 0;
while((i = in.read(b)) > 0){
outp.write(b, 0, i);
}
outp.flush();
}
catch(Exception e)
{
//System.out.println("Error!");
logger.error(e.getMessage(),e);
}
finally
{
if(in != null)
{
in.close();
in = null;
}
if(outp != null)
{
outp.close();
outp = null;
}
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doPost(request, response);
//System.out.println("下载");
response.setContentType("application/x-download");
PropertyBean propertyBeanURL = new PropertyBean();
propertyBeanURL.setPropertiesFile("mail.properties");
propertyBeanURL.init();
String tempUrl = propertyBeanURL.get("temp");
String filePath = tempUrl+ File.separatorChar+ "CrmUpload" +File.separatorChar;
String filedownload = filePath + "tcsl_mobile.xls";
//String filePath = getPropertyBean("ticketFilePath"); //"E:\\CrmUpload\\";
//String filedownload = filePath + getPropertyBean("ticketTemplatesFile"); //filePath + "mobile.xls";//文件名
String filedisplay = "非会员电话号码模版.xls";//下载文件时显示的文件保存名称
String filenamedisplay = URLEncoder.encode(filedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
OutputStream outp = null;
FileInputStream in = null;
try
{
outp = response.getOutputStream();
File truefile=new File(filedownload);
in = new FileInputStream(truefile);
byte[] b = new byte[1024];
int i = 0;
while((i = in.read(b)) > 0){
outp.write(b, 0, i);
}
outp.flush();
}
catch(Exception e)
{
//System.out.println("Error!");
logger.error(e.getMessage(),e);
}
finally
{
if(in != null)
{
in.close();
in = null;
}
if(outp != null)
{
outp.close();
outp = null;
}
}
}
接收文件(此例是接收xls文件,并解析)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
final long MAX_SIZE = 1024 * 1024 * 1;// 设置上传文件最大为1G 1B *1024 = 1*1024 = 1M *1024 = 1G
// 上传文件路径
//String filePath = getPropertyBean("ticketFilePath"); //"E:\\CrmUpload\\";
PropertyBean propertyBeanURL = new PropertyBean();
propertyBeanURL.setPropertiesFile("mail.properties");
propertyBeanURL.init();
String tempUrl = propertyBeanURL.get("temp");
String filePath = tempUrl+ File.separatorChar+ "CrmUpload" +File.separatorChar;
//System.out.println(filePath);
try {
checkPath(filePath);
} catch (Exception e1) {
e1.printStackTrace();
}
// 临时存放目录
String tempPath = filePath + "temp"+File.separator;
try {
checkPath(tempPath);
} catch (Exception e1) {
e1.printStackTrace();
}
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
// 设置上传文件时用于临时存放文件的内存大小,这里是5M.多于的部分将临时存在硬盘
dfif.setSizeThreshold(1024 * 1024 * 5);
// 设置存放临时文件的目录
dfif.setRepository(new File(tempPath));
// 用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(dfif);
// 设置最大上传尺寸
sfu.setSizeMax(MAX_SIZE);
// 从request得到 所有 上传域的列表
List fileList = null;
try {
fileList = sfu.parseRequest(request);
} catch (FileUploadException e) {// 处理文件尺寸过大异常
if (e instanceof SizeLimitExceededException) {
//System.out.println("导入文件大小不能超过1M");
out.println(showMsg("导入文件大小不能超过1M!"));
return;
}
logger.error(e.getMessage(),e);
}
// 没有选择上传文件
if (fileList == null || fileList.size() == 0) {
//System.out.println("请选择导入文件");
out.println(showMsg("请选择导入文件"));
return;
}
// 得到所有上传的文件
Iterator fileItr = fileList.iterator();
// 循环处理所有文件
while (fileItr.hasNext()) {
FileItem fileItem = null;
String path = null;
double size = 0;
// 得到当前文件
fileItem = (FileItem) fileItr.next();
// 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
if (fileItem == null || fileItem.isFormField()) {
continue;
}
// 得到文件的完整路径
path = fileItem.getName();
// 得到文件的大小
size = fileItem.getSize();
// 得到去除路径的文件名
String t_name = path.substring(path.lastIndexOf(File.separator) + 1);
// 得到文件的扩展名(无扩展名时将得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
if (!"xls".equalsIgnoreCase(t_ext)) {
out.println(showMsg("请使用正确的电话号码模版文件导入!"));
break;
}
//生成文件名
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
String newname = sdf.format((new Date()).getTime());
t_name = newname + RandomStringUtils.randomNumeric(3);
// 保存的最终文件完整路径,保存在e盘upload目录下
String u_name = filePath + t_name + "." + t_ext;
String u_size = "";
try {
// 保存文件
fileItem.write(new File(u_name));
if (size > 1024 * 1024)
u_size = (float) Math.round(size * 100 / (1024 * 1024)) / 100 + "MB";
else
u_size = (float) Math.round(size * 100 / 1024) / 100 + "KB";
//System.out.println("文件名:" + t_name + "上传完成。文件大小:" + u_size);
out.println(showMsg("导入文件加载完毕,正在解析,请稍候..."));
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(u_name));
HSSFWorkbook workBook = new HSSFWorkbook(fs);
try {
HSSFSheet sheet = workBook.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
rows = 3001; //1万行数据
if (rows > 0) {
sheet.getMargin(Sheet.TopMargin);
List<MobileListDto> list = new ArrayList<MobileListDto>();
for (int j = 1; j < rows; j++) { //从第2行开始
HSSFRow row = sheet.getRow(j);
if (row == null) {
continue;
}
int cells = row.getLastCellNum(); // 是获取最后一个不为空的列是第几个
if (cells < 1){
out.println(showMsg("电话号码文件格式不符合要求!"));
break;
}
HSSFCell cell0 = row.getCell(0); //姓名列
HSSFCell cell1 = row.getCell(1); //手机号码列
// System.out.println(cell.getRichStringCellValue());
MobileListDto mld = new MobileListDto();
String rname = "";
String rmobile = "";
if (cell0 != null){
switch (cell0.getCellType()) {
case Cell.CELL_TYPE_STRING:
rname = cell0.getRichStringCellValue().toString();
break;
case Cell.CELL_TYPE_NUMERIC:
rname = new DecimalFormat("0").format(cell0.getNumericCellValue());
break;
}
} else {
rname = "";
}
if (cell1!=null) {
switch (cell1.getCellType()) {
case Cell.CELL_TYPE_STRING:
rmobile = cell1.getRichStringCellValue().toString();
break;
case Cell.CELL_TYPE_NUMERIC:
rmobile = new DecimalFormat("0").format(cell1.getNumericCellValue());
break;
}
} else {
rmobile = "";
}
rmobile = checkMobile(rmobile);
if ("".equals(rname)){
rname = "未知";
}
//System.out.println(rname +"--"+rmobile);
// 手机号不为空 且 都是数字号码
if (!"".equals(rmobile) && NumberUtils.isNumber(rmobile)){
mld.setcName(rname);
mld.setcMobile(rmobile);
list.add(mld);
}
}
// 去除重复
list = removeDuplicateWithOrder(list);
if (list != null && !list.isEmpty()) {
//System.out.println("开始json");
//若list不为空,则将其转换成JSON对象,并存入jsonArray中
JSONArray jsonArray = JSONArray.fromObject(list);
//下面就是把存有查询结果的JSON对象返给页面
//System.out.println(jsonArray);
out.println("<script type=\"text/javascript\">parent.rtnList("+jsonArray+");</script>");
}
out.println(showMsg("共成功导入" + String.valueOf(list.size())+"个手机号码!"));
}
out.flush();
out.close();
delFile(u_name);
} catch (Exception e) {
out.println(showMsg("电话号码文件解析出错!"));
delFile(u_name);
logger.error(e.getMessage(),e);
}
} catch (Exception e) {
out.println(showMsg("电话号码文件导入出现异常!"));
delFile(u_name);
logger.error(e.getMessage(),e);
}
}
}
}
private void checkPath(String filepath) throws Exception {
File file = new File(filepath);
if (!file.exists() || !file.isDirectory()) {
file.mkdirs();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
final long MAX_SIZE = 1024 * 1024 * 1;// 设置上传文件最大为1G 1B *1024 = 1*1024 = 1M *1024 = 1G
// 上传文件路径
//String filePath = getPropertyBean("ticketFilePath"); //"E:\\CrmUpload\\";
PropertyBean propertyBeanURL = new PropertyBean();
propertyBeanURL.setPropertiesFile("mail.properties");
propertyBeanURL.init();
String tempUrl = propertyBeanURL.get("temp");
String filePath = tempUrl+ File.separatorChar+ "CrmUpload" +File.separatorChar;
//System.out.println(filePath);
try {
checkPath(filePath);
} catch (Exception e1) {
e1.printStackTrace();
}
// 临时存放目录
String tempPath = filePath + "temp"+File.separator;
try {
checkPath(tempPath);
} catch (Exception e1) {
e1.printStackTrace();
}
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
// 设置上传文件时用于临时存放文件的内存大小,这里是5M.多于的部分将临时存在硬盘
dfif.setSizeThreshold(1024 * 1024 * 5);
// 设置存放临时文件的目录
dfif.setRepository(new File(tempPath));
// 用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(dfif);
// 设置最大上传尺寸
sfu.setSizeMax(MAX_SIZE);
// 从request得到 所有 上传域的列表
List fileList = null;
try {
fileList = sfu.parseRequest(request);
} catch (FileUploadException e) {// 处理文件尺寸过大异常
if (e instanceof SizeLimitExceededException) {
//System.out.println("导入文件大小不能超过1M");
out.println(showMsg("导入文件大小不能超过1M!"));
return;
}
logger.error(e.getMessage(),e);
}
// 没有选择上传文件
if (fileList == null || fileList.size() == 0) {
//System.out.println("请选择导入文件");
out.println(showMsg("请选择导入文件"));
return;
}
// 得到所有上传的文件
Iterator fileItr = fileList.iterator();
// 循环处理所有文件
while (fileItr.hasNext()) {
FileItem fileItem = null;
String path = null;
double size = 0;
// 得到当前文件
fileItem = (FileItem) fileItr.next();
// 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
if (fileItem == null || fileItem.isFormField()) {
continue;
}
// 得到文件的完整路径
path = fileItem.getName();
// 得到文件的大小
size = fileItem.getSize();
// 得到去除路径的文件名
String t_name = path.substring(path.lastIndexOf(File.separator) + 1);
// 得到文件的扩展名(无扩展名时将得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
if (!"xls".equalsIgnoreCase(t_ext)) {
out.println(showMsg("请使用正确的电话号码模版文件导入!"));
break;
}
//生成文件名
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
String newname = sdf.format((new Date()).getTime());
t_name = newname + RandomStringUtils.randomNumeric(3);
// 保存的最终文件完整路径,保存在e盘upload目录下
String u_name = filePath + t_name + "." + t_ext;
String u_size = "";
try {
// 保存文件
fileItem.write(new File(u_name));
if (size > 1024 * 1024)
u_size = (float) Math.round(size * 100 / (1024 * 1024)) / 100 + "MB";
else
u_size = (float) Math.round(size * 100 / 1024) / 100 + "KB";
//System.out.println("文件名:" + t_name + "上传完成。文件大小:" + u_size);
out.println(showMsg("导入文件加载完毕,正在解析,请稍候..."));
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(u_name));
HSSFWorkbook workBook = new HSSFWorkbook(fs);
try {
HSSFSheet sheet = workBook.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
rows = 3001; //1万行数据
if (rows > 0) {
sheet.getMargin(Sheet.TopMargin);
List<MobileListDto> list = new ArrayList<MobileListDto>();
for (int j = 1; j < rows; j++) { //从第2行开始
HSSFRow row = sheet.getRow(j);
if (row == null) {
continue;
}
int cells = row.getLastCellNum(); // 是获取最后一个不为空的列是第几个
if (cells < 1){
out.println(showMsg("电话号码文件格式不符合要求!"));
break;
}
HSSFCell cell0 = row.getCell(0); //姓名列
HSSFCell cell1 = row.getCell(1); //手机号码列
// System.out.println(cell.getRichStringCellValue());
MobileListDto mld = new MobileListDto();
String rname = "";
String rmobile = "";
if (cell0 != null){
switch (cell0.getCellType()) {
case Cell.CELL_TYPE_STRING:
rname = cell0.getRichStringCellValue().toString();
break;
case Cell.CELL_TYPE_NUMERIC:
rname = new DecimalFormat("0").format(cell0.getNumericCellValue());
break;
}
} else {
rname = "";
}
if (cell1!=null) {
switch (cell1.getCellType()) {
case Cell.CELL_TYPE_STRING:
rmobile = cell1.getRichStringCellValue().toString();
break;
case Cell.CELL_TYPE_NUMERIC:
rmobile = new DecimalFormat("0").format(cell1.getNumericCellValue());
break;
}
} else {
rmobile = "";
}
rmobile = checkMobile(rmobile);
if ("".equals(rname)){
rname = "未知";
}
//System.out.println(rname +"--"+rmobile);
// 手机号不为空 且 都是数字号码
if (!"".equals(rmobile) && NumberUtils.isNumber(rmobile)){
mld.setcName(rname);
mld.setcMobile(rmobile);
list.add(mld);
}
}
// 去除重复
list = removeDuplicateWithOrder(list);
if (list != null && !list.isEmpty()) {
//System.out.println("开始json");
//若list不为空,则将其转换成JSON对象,并存入jsonArray中
JSONArray jsonArray = JSONArray.fromObject(list);
//下面就是把存有查询结果的JSON对象返给页面
//System.out.println(jsonArray);
out.println("<script type=\"text/javascript\">parent.rtnList("+jsonArray+");</script>");
}
out.println(showMsg("共成功导入" + String.valueOf(list.size())+"个手机号码!"));
}
out.flush();
out.close();
delFile(u_name);
} catch (Exception e) {
out.println(showMsg("电话号码文件解析出错!"));
delFile(u_name);
logger.error(e.getMessage(),e);
}
} catch (Exception e) {
out.println(showMsg("电话号码文件导入出现异常!"));
delFile(u_name);
logger.error(e.getMessage(),e);
}
}
}
}
private void checkPath(String filepath) throws Exception {
File file = new File(filepath);
if (!file.exists() || !file.isDirectory()) {
file.mkdirs();
}
}