Java文件file上传到服务器并读取指定目录下文件(含解压缩)

Java读取上传文件,并保存到服务器,并在服务器端进行解压缩:

package com.msunsoft.common.upload.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.activation.DataHandler;
import javax.jws.WebService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ContextLoader;

import com.csvreader.CsvReader;
import com.msunsoft.common.upload.dao.DataReportImportHs4Dao;
import com.msunsoft.common.upload.model.ImportData;
import com.msunsoft.common.web.SpringContextHolder;
import com.msunsoft.configuration.authorization.service.ComUserService;
import com.msunsoft.configuration.reportperiod.service.ComMrhpPeriodService;
import com.msunsoft.datacollection.quarterlyReportQuery.model.MrhpPeriod;
import com.msunsoft.datacollection.quarterlyReportQuery.model.MrhpPeriodGrade;
import com.msunsoft.datacollection.reportsubmitandaudit.dao.RhsaHs412013Dao;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;

@WebService()
public class ClientDataReportService {

	@Autowired
	public ComUserService comUserService;

	@Autowired
	public ComMrhpPeriodService comMrhpPeriodService;

	@Autowired
	public RhsaHs412013Dao rhsaHs412013Dao;

	/**
	 * 客户端上传首页数据
	 * 
	 * @param username
	 * @param password
	 * @param data
	 * @return
	 */
	public String HPMRDataReport(String username, String password, String periodId, DataHandler data) {
		// 获取报表锁定服务
		// RhsaReportLockService rhsaReportLockService = (RhsaReportLockService)
		// SpringContextHolder.getBean("rhsaReportLockService");
		// 获取报表期服务
		MrhpPeriodService mrhpPeriodService = (MrhpPeriodService) SpringContextHolder.getBean("mrhpPeriodService");
		// // 获取报表期
		// MrhpPeriod period = mrhpPeriodService.get(periodId);

		// 获取user
		HashMap<String, Object> userhp = comUserService.selectLoginInfo(username);

		// 获取org_id和org_name
		if (userhp == null) {
			// 用户名非法,不允许上报
			return "0001";
		}
		String orgId = userhp.get("orgid") + "";

		if (comMrhpPeriodService.lockPeriod(periodId, orgId)) {
			// 该机构该报表期已经锁定,不允许上报
			return "0002";
		}

		String orgPeriod = mrhpPeriodService.getOrgPreviousGradePeriod(MrhpPeriodGrade.SEASON, null).getId();
		if (!orgPeriod.equals(periodId)) {
			// 此报表期暂未开放上报,请等待报表期开放后再进行上报
			return "0003";
		}

		try {
			// 上传文件存放路径
			String uploadPath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
			if (File.separator.equals(uploadPath.charAt(uploadPath.length() - 1) + "")) {
				uploadPath = uploadPath + "zipFiles";
			} else {
				uploadPath = uploadPath + File.separator + "zipFiles";
			}
			File path = new File(uploadPath);
			if (!path.exists()) {// 判断文件夹是否存在
				path.mkdir();
			}
			// 上传文件名
			String fileName = this.getCurrentTime() + username;
			// 存储上传的zip文件
			this.SaveFileFromInputStream(data.getInputStream(), uploadPath, fileName + ".zip");

			// 解压文件存放路径
			String unZipFilePath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
			if (File.separator.equals(unZipFilePath.charAt(unZipFilePath.length() - 1) + "")) {
				unZipFilePath = unZipFilePath + "csvFiles";
			} else {
				unZipFilePath = unZipFilePath + File.separator + "csvFiles";
			}
			// 解压zip文件,获取csv文件
			String csvFileName = unzipFile(uploadPath, fileName, unZipFilePath);
			if (null == csvFileName) {
				// 文件损毁,无法读取,请尝试再次上报!
				return "0004";
			}
			if (readCSV(csvFileName, username)) {
				// 上报成功
				return "0000";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "0005";
	}

	/**
	 * 解压ZIP文件,获得csv
	 * 
	 * @param Path
	 * @param fileName
	 * @param unZipFilePath
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private String unzipFile(String Path, String fileName, String unZipFilePath) {
		String file = null;
		File temppath = new File(unZipFilePath);
		if (!temppath.exists()) {// 判断文件夹是否存在
			temppath.mkdir();
		}

		ZipFile zipFile;
		try {
			zipFile = new ZipFile(Path + File.separator + fileName + ".zip"); // 压缩文件

			zipFile.setFileNameCharset("GBK");

			zipFile.extractAll(unZipFilePath);

			List<FileHeader> headerList = zipFile.getFileHeaders();

			for (FileHeader fileHeader : headerList) {
				if (!fileHeader.isDirectory()) {
					// 获取文件名
					file = fileHeader.getFileName();
				}
			}
		} catch (ZipException e) {
			e.printStackTrace();
		}
		return unZipFilePath + File.separator + file;
	}

	/**
	 * 保存文件
	 * 
	 * @param file
	 * @param name
	 */
	@SuppressWarnings("unused")
	private void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
		String filePath = path + "/" + filename;
		FileOutputStream fs = new FileOutputStream(filePath);
		byte[] buffer = new byte[1024 * 1024];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
	}

	/**
	 * 读取csv文件
	 * 
	 * @param fileName
	 * @return
	 */
	private boolean readCSV(String fileName, String username) {
		// 获取导入数据的dao
		DataReportImportHs4Dao dataReportImportDao = (DataReportImportHs4Dao) SpringContextHolder
				.getBean("dataReportImportHs4Dao");
		// 获取报表期服务
		MrhpPeriodService mrhpPeriodService = (MrhpPeriodService) SpringContextHolder.getBean("mrhpPeriodService");
		// 获取报表期
		MrhpPeriod period = mrhpPeriodService.getOrgPreviousGradePeriod(MrhpPeriodGrade.SEASON, null);
		// 上报数据量记录detail service
		// RhsaHs4ImportDetailService detailService =
		// (RhsaHs4ImportDetailService)
		// SpringContextHolder.getBean("rhsaHs4ImportDetailService");

		// 获取user
		HashMap<String, Object> userhp = comUserService.selectLoginInfo(username);
		// 获取org_id和org_name
		if (userhp == null) {
			return false;
		}

		String orgId = userhp.get("orgid") + "";
		String orgName = userhp.get("orgname") + "";
		String orgCode = userhp.get("orgid") + "";
		// 获取dataReportService
		DataReportImportService dataReportImportService = (DataReportImportService) SpringContextHolder
				.getBean("dataReportImportService");
		// 获取ImportData
		ImportData importData = dataReportImportService.initImportData("RHSA_HS4_1_2013_TEMP", "WT4_1", period.getId(),
				orgId, orgName, orgCode);
		String tableName = "RHSA_HS4_1_2013_TEMP";
		// 获取RhsaHs412013Service
		// RhsaHs412013Service rhsaHs412013Service = (RhsaHs412013Service)
		// SpringContextHolder.getBean("rhsaHs412013Service");
		CsvReader reader = null;
		// BufferedReader reader = null;
		try {
			// 初始化CsvReader并指定列分隔符和字符编码
			reader = new CsvReader(fileName, ',', Charset.forName("GBK"));
			// reader = new BufferedReader(new InputStreamReader(new
			// FileInputStream(new File(fileName)),"GBK"));
			// String line = null;
			// 读取标题信息
			reader.readRecord();
			// line = reader.readLine();
			String title[] = reader.getValues();
			while (reader.readRecord()) {
				// dataMap存储读取数据
				Map<String, Object> dataMap = new HashMap<String, Object>();
				// 读取每行数据以数组形式返回
				String item[] = reader.getValues();
				for (int i = 0; i < item.length; i++) {
					if ("".equals(item[i])) {
						dataMap.put(title[i].replace("\"", ""), null);
					} else {
						// 数据存放到dataMap,并去除""引号
						dataMap.put(title[i].replace("\"", ""), item[i].replace("\"", ""));
					}

				}
				dataReportImportDao.clientDataUpload(dataMap, importData, false);
			}
			dataReportImportDao.clientDataUpload(null, importData, true);
			// 重置上报数量明细
			// detailService.reset(importData.getTableName(),
			// importData.getOrgId(), importData.getPeriod());
			// 变更为已上报状态
			// rhsaHs412013Service.report(importData.getPeriod(), orgId);
			rhsaHs412013Dao.report(importData.getPeriod(), orgId,tableName);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (reader != null){
			 // 关闭CsvReader
                reader.close();
			}
				
		}
		return true;
	}

	/**
	 * 获取当前系统时间日期
	 */
	private String getCurrentTime() {
		Calendar ca = Calendar.getInstance();
		ca.setTime(new java.util.Date());
		SimpleDateFormat simpledate = new SimpleDateFormat("yyyyMMddHHmmddsss");
		return simpledate.format(ca.getTime());
	}

}

猜你喜欢

转载自blog.csdn.net/sinat_25311845/article/details/87920216
今日推荐