文件上传,文件下载,解压zip文件,判断压缩文件里面包含几个文件,判断压缩文件里是否包含指定的后缀文件

package com.sinosoft.mis.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.sinosoft.cms.common.util.SFTPUtil;
import com.sinosoft.cms.common.util.SystemParameters;
import com.sinosoft.transverse.common.Data;

public class Jun implements JunService {
private static Workbook wb;
private static ChannelSftp sftp;

private static Session session;
/** SFTP 登录用户名*/
private static String username;
/** SFTP 登录密码*/
private static String password;
/** 私钥 */
private static String privateKey;
/** SFTP 服务器地址IP地址*/
private static String host;
/** SFTP 端口*/
private static int port;

/**
* 下载文件
* @return
*/
public String downloadFile(){

Map params = Data.getParametersFromRequest(super.getRequest());
String ftpPathHead = SystemParameters.FTPpath;//FTP文件服务器基础路径
String ftpPathTail = (String) params.get("ftpPath");//FTP基础路径后路径
String ftpPath = ftpPathHead+ftpPathTail;//
ftpPath = ftpPath.replaceAll("//", "/");//FTP储存文件路径
String rootPath = super.getRequest().getSession().getServletContext().getRealPath("/");//项目根目录
String downloadPath = rootPath+"downloadFile/";
String returnPath = SFTPUtil.downloadFile(ftpPath,downloadPath);
returnPath = returnPath.substring(returnPath.lastIndexOf("vehiclesMIS"));
StringBuffer requestURL = super.getRequest().getRequestURL();
String url = requestURL.substring(0, requestURL.indexOf("vehiclesMIS"))+returnPath;
url = url.replaceAll("\\\\", "/");
StringBuffer sb = new StringBuffer();
sb.append("<script type=\"text/javascript\">\n");
sb.append("window.location.href='"+url+"';\n");
sb.append("</script>");
super.renderHtml(sb.toString());
return null;
}

public String editInsSubmit(Map params, File underFile, HttpServletRequest request) {

String underFileDown = "";//上传后的下载路径
if(underFile!=null){
String underFilePath = underFile.getAbsolutePath();//文件路径
underFilePath = underFilePath.substring(0, underFilePath.lastIndexOf(".")+1);
underFile.renameTo(new File(underFilePath+"zip"));//修改文件后缀名
underFilePath = underFilePath.replaceAll("\\\\", "/");
String conContrZipPath = underFilePath.substring(0, underFilePath.lastIndexOf("."))+"/";
//解压压缩文件
String conUnZipPath = Jun.unZip(underFilePath+"zip", conContrZipPath);
//判断压缩文件里的个数,或知否保函什么文件(有无xls的文件)
// List<String> conUnZipPath = UnZip.unZip(uploadDataPath, conContrZipPath);
// int size = conUnZipPath.size();
String result = readFile(conContrZipPath);
if(result=="Y"){
}else{
StringBuffer sb = new StringBuffer();
sb.append("<script type=\"text/javascript\">\n");
sb.append("alert(\""+result+"\")\n");
sb.append("window.history.go(-1)\n");
sb.append("</script>");
return sb.toString();
}
//上传文件,返回下载路径
underFileDown = uploadFile(underFilePath+"zip",request);
if(underFileDown==null){
StringBuffer sb = new StringBuffer();
sb.append("<script type=\"text/javascript\">\n");
sb.append("alert(\"上传安全责任险核保信息文件异常!请检查路径及文件类型是否正确!\")\n");
sb.append("window.history.go(-1)\n");
sb.append("</script>");
return sb.toString();
}else{
//下载路径存库
}
}
return null;

}

/**
* 解压文件
* @param zipFile 目标文件
* @param descDir 指定解压目录
* @param urlList 存放解压后的文件目录(可选)
* @return
*/
public static String unZip(String zipPath, String descDir) {
File zipFile = new File(zipPath);
boolean flag = false;
File pathFile = new File(descDir);
if(!pathFile.exists()){
pathFile.mkdirs();
}
ZipFile zip = null;
try {
//指定编码,否则压缩包里面不能有中文目录
zip = new ZipFile(zipFile, Charset.forName("gbk"));
String returnStr = "";
for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir+zipEntryName).replace("/", File.separator);
returnStr = zipEntryName;
//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
if(!file.exists()){
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(new File(outPath).isDirectory()){
continue;
}
//保存文件路径信息
// urlList.add(outPath);

OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[2048];
int len;
while((len=in.read(buf1))>0){
out.write(buf1,0,len);
}
in.close();
out.close();
}
//必须关闭,否则无法删除该zip文件
zip.close();
if(returnStr.lastIndexOf("/")>-1){
returnStr = returnStr.substring(0,returnStr.lastIndexOf("/"));
}
return returnStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}

}

/**
* 上传文件
* 返回null表示上传异常
* @return
*/
public String uploadFile(String path, HttpServletRequest request){
//将上传的文件写到服务器上指定的文件。
String ftpPath = SFTPUtil.uploadFiles(path,"insins");
if(ftpPath==null){
return null;
}else{
ftpPath = ftpPath.substring(ftpPath.indexOf("ftpFile")+7);
StringBuffer requestURL = request.getRequestURL();
String url = requestURL.substring(0, requestURL.indexOf("项目名")+19);
url = url+"/ceshi/downloadFile.do?ftpPath=\""+ftpPath+"\"";
// super.renderText(url);
return url;
}
}

/**
* 上传文件工具类方法
* @param path 上传文件路径
* @param FTPpathName 希望在文件服务器创建的文件夹名称(可以为null)
*/
public static String uploadFiles(String path,String FTPpathName){
try {
String suffixName = path.substring(path.lastIndexOf(".") + 1);//获取文件后缀名
String newName = randomTime()+"."+suffixName;//文件的新名字
host = "192.168.0.1";//服务器地址
port = 88;//端口
username = "root";//用户名
password = "000000";//密码
String FTPpath= "/PolicyManagement/ftpFile/";//FTP基础路径
SFTPUtil sftp = new SFTPUtil(username, password, host, port);
sftp.login();
File file = new File(path);
InputStream is = new FileInputStream(file);
Date date = new Date();
String str = "yyyMMdd";
SimpleDateFormat sdf = new SimpleDateFormat(str);
String timePath = sdf.format(date);
if(FTPpathName==null||"".equals(FTPpathName)){
FTPpathName = "/"+timePath+"/";
}else{
FTPpathName = "/"+timePath+"/"+FTPpathName+"/";
}

sftp.upload(FTPpath,FTPpathName, newName, is);
sftp.logout();

String returnPath = FTPpath+FTPpathName+newName;
returnPath = returnPath.replace("//", "/");
return returnPath;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

public static String randomTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyMMdd");
String timePath = sdf.format(new Date());
long r = 0;
int i = 0;
while(true) {
r = System.currentTimeMillis();
//取模 也就是1----99的随机数
i = (int)(r % 100);
if(0 != i) {
break;
}
}
// System.out.println(r);
// System.out.printf("%d \n",i);
return String.valueOf(timePath+r);
}

public static List<String> unZipTest(String zipPath, String descDir) {
File zipFile = new File(zipPath);
boolean flag = false;
File pathFile = new File(descDir);
if(!pathFile.exists()){
pathFile.mkdirs();
}
ZipFile zip = null;
try {
//指定编码,否则压缩包里面不能有中文目录
zip = new ZipFile(zipFile, Charset.forName("gbk"));
String returnStr = "";
List<String> entrys = new ArrayList<>();
for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryName = entry.getName();
entrys.add(zipEntryName);
InputStream in = zip.getInputStream(entry);
String outPath = (descDir+zipEntryName).replace("/", File.separator);
returnStr = zipEntryName;
//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
if(!file.exists()){
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(new File(outPath).isDirectory()){
continue;
}
//保存文件路径信息
// urlList.add(outPath);

OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[2048];
int len;
while((len=in.read(buf1))>0){
out.write(buf1,0,len);
}
in.close();
out.close();
}
//必须关闭,否则无法删除该zip文件
zip.close();
if(returnStr.lastIndexOf("/")>-1){
returnStr = returnStr.substring(0,returnStr.lastIndexOf("/"));
}
return entrys;
} catch (IOException e) {
e.printStackTrace();
return null;
}

}

public String readFile(String filePath) {
File file = new File(filePath);
if (file.isDirectory()) {
String[] fileList = file.list();
for (int i = 0, len = fileList.length; i < len; i++) {
File readFile = new File(filePath + fileList[i]);
if (readFile.isDirectory()) {
return "请不要包含多层文件夹!";
} else if (!readFile.isDirectory()) {
// 这里不用判断文件类型,只要是文件就行,在下面这个方法里面判断文件
String fileName = readFile.getName();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if("xls".equals(suffix)||"xlsx".equals(suffix)){
return parsingFile(readFile);
}
}
}
}else if(!file.isDirectory()){
String fileName = file.getName();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if("xls".equals(suffix)||"xlsx".equals(suffix)){
return parsingFile(file);
}else {
return "请上传含有Excel的文件!";
}
}
return "请上传含有Excel的文件!";
}

public String parsingFile(File fileExcel) {
try{
int position = fileExcel.getName().lastIndexOf(".");
if (position < 0){
return "只能上传含后缀的文件!";
}
InputStream is = new FileInputStream(fileExcel.getPath());
if(fileExcel.getName().endsWith(".xls")){
wb = new HSSFWorkbook(is);
}else if(fileExcel.getName().endsWith(".xlsx")){
wb = new XSSFWorkbook(is);
}
//执行循环表行
}catch(Exception e){
e.printStackTrace();
return"上传文件数据有误";
}
return null;
}
}

posted on 2020-08-06 11:37  多言  阅读(1744)  评论(0编辑  收藏  举报

导航