Browse Source

支持zip模板压缩包上传

sunyj 9 years ago
parent
commit
fb5a59b6d4

+ 26 - 28
src/main/java/com/uas/report/controller/UploadController.java

@@ -12,6 +12,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.multipart.MultipartFile;
 import org.springframework.web.multipart.MultipartFile;
 
 
 import com.uas.report.support.JasperserverRestAPIConf;
 import com.uas.report.support.JasperserverRestAPIConf;
+import com.uas.report.util.ZipUtils;
 
 
 @Controller
 @Controller
 @RequestMapping("/upload")
 @RequestMapping("/upload")
@@ -32,41 +33,53 @@ public class UploadController {
 	 */
 	 */
 	@RequestMapping("")
 	@RequestMapping("")
 	@ResponseBody
 	@ResponseBody
-	public String upload(String userName, MultipartFile file) {
+	public String upload(final String userName, String fileType, MultipartFile file) {
 		String message = "";
 		String message = "";
 		if (StringUtils.isEmpty(userName)) {
 		if (StringUtils.isEmpty(userName)) {
 			message = "未传入当前账套用户名!";
 			message = "未传入当前账套用户名!";
 			logger.error(message);
 			logger.error(message);
 			return message;
 			return message;
 		}
 		}
-
 		if (file == null || file.isEmpty()) {
 		if (file == null || file.isEmpty()) {
 			message = "文件为空,无法进行上传!";
 			message = "文件为空,无法进行上传!";
 			logger.error(message);
 			logger.error(message);
 			return message;
 			return message;
 		}
 		}
+		if (StringUtils.isEmpty(fileType)) {
+			fileType = "jrxml";
+		}
 
 
 		String fileName = file.getOriginalFilename();
 		String fileName = file.getOriginalFilename();
-		StringBuilder stringBuilder = new StringBuilder(jsRestAPIConf.getLocalBaseDir()).append("/").append(userName)
-				.append("/");
-		// 上传图片
-		if (file.getContentType().contains("image")) {
-			stringBuilder.append("Picture").append("/");
-		}
-		// 上传报表模板
-		else if (isReportTemplate(fileName)) {
-			stringBuilder.append("jrxml").append("/");
+		StringBuilder stringBuilder = new StringBuilder(jsRestAPIConf.getLocalBaseDir()).append("/");
+		// jrxml模板和图片分别放在jrxml和Picture文件夹下,其他资源放在当前账套根路径下
+		if (fileType.equals("jrxml")) {
+			stringBuilder.append(userName).append("/").append("jrxml").append("/");
+		} else if (fileType.equals("image")) {
+			stringBuilder.append(userName).append("/").append("Picture").append("/");
+		} else if (fileType.equals("other")) {
+			stringBuilder.append(userName).append("/");
 		}
 		}
+
 		stringBuilder.append(fileName);
 		stringBuilder.append(fileName);
 		String targetFilePath = stringBuilder.toString();
 		String targetFilePath = stringBuilder.toString();
-		File targetFile = new File(targetFilePath);
+		final File targetFile = new File(targetFilePath);
 		if (!targetFile.exists()) {
 		if (!targetFile.exists()) {
 			targetFile.mkdirs();
 			targetFile.mkdirs();
 		}
 		}
 		try {
 		try {
 			file.transferTo(targetFile);
 			file.transferTo(targetFile);
-			message = "成功上传文件至:" + targetFile.getCanonicalPath();
+			message = "成功上传文件至:" + targetFile.getPath();
 			logger.info(message);
 			logger.info(message);
+			// 如果上传的是模板zip包,将其解压到相应的账套下
+			if (fileType.equals("zip")) {
+				new Thread(new Runnable() {
+					@Override
+					public void run() {
+						ZipUtils.unzip(targetFile.getPath(),
+								new File(targetFile.getPath()).getParent() + File.separator + userName);
+					}
+				}).start();
+			}
 			return message;
 			return message;
 		} catch (IllegalStateException | IOException e) {
 		} catch (IllegalStateException | IOException e) {
 			e.printStackTrace();
 			e.printStackTrace();
@@ -77,19 +90,4 @@ public class UploadController {
 		return message;
 		return message;
 	}
 	}
 
 
-	/**
-	 * 判断是否为jrxml报表模板文件
-	 * 
-	 * @param fileName
-	 * @return
-	 */
-	private boolean isReportTemplate(String fileName) {
-		if (StringUtils.isEmpty(fileName)) {
-			return false;
-		}
-		if (fileName.endsWith("jrxml")) {
-			return true;
-		}
-		return false;
-	}
 }
 }

+ 143 - 0
src/main/java/com/uas/report/util/ZipUtils.java

@@ -0,0 +1,143 @@
+package com.uas.report.util;
+
+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.util.Enumeration;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipOutputStream;
+
+import org.apache.log4j.Logger;
+
+import com.alibaba.druid.util.StringUtils;
+import com.uas.report.core.exception.ReportException;
+
+/**
+ * 压缩工具类
+ * 
+ * @author sunyj
+ * @since 2016年11月1日 下午4:51:38
+ */
+public class ZipUtils {
+
+	private static final Logger logger = Logger.getLogger(ZipUtils.class);
+
+	/**
+	 * 压缩文件夹
+	 * 
+	 * @param sourceFolderPath
+	 *            将压缩的文件夹
+	 * @param zipFilePath
+	 *            压缩后的压缩包路径
+	 */
+	public static void zipFolder(String sourceFolderPath, String zipFilePath) {
+		if (StringUtils.isEmpty(sourceFolderPath) || StringUtils.isEmpty(zipFilePath)) {
+			return;
+		}
+		File folder = new File(sourceFolderPath);
+		if (!folder.exists() || !folder.isDirectory()) {
+			throw new ReportException("该路径不存在或并非文件夹:" + sourceFolderPath);
+		}
+		File[] files = folder.listFiles();
+		if (files.length < 0) {
+			throw new ReportException("空文件夹:" + sourceFolderPath);
+		}
+
+		try {
+			ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFilePath));
+			putNextEntryFromFolder(zipOutputStream, folder, "");
+			zipOutputStream.close();
+			logger.info("zip completed");
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+
+	/**
+	 * 递归将文件夹下的文件进行压缩
+	 * 
+	 * @param zipOutputStream
+	 *            压缩包的输出流
+	 * @param folder
+	 *            需要压缩的文件夹
+	 * @param prefix
+	 *            为保持压缩后的路径层次不变,所记录的当前文件夹的相对层级
+	 */
+	private static void putNextEntryFromFolder(ZipOutputStream zipOutputStream, File folder, String prefix) {
+		File[] files = folder.listFiles();
+		try {
+			for (File file : files) {
+				logger.info("zip... " + prefix + file.getName());
+				if (file.isDirectory()) {
+					putNextEntryFromFolder(zipOutputStream, file, prefix + file.getName() + File.separator);
+				} else {
+					zipOutputStream.putNextEntry(new ZipEntry(prefix + file.getName()));
+					InputStream inputStream = new FileInputStream(file);
+					int b;
+					while ((b = inputStream.read()) != -1) {
+						zipOutputStream.write(b);
+					}
+					inputStream.close();
+				}
+			}
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+
+	/**
+	 * 解压缩
+	 * 
+	 * @param zipFilePath
+	 *            将解压缩的压缩包路径
+	 * @param zipFilePath
+	 *            解压缩后的文件路径
+	 */
+	public static void unzip(String zipFilePath, String folderPath) {
+		if (StringUtils.isEmpty(zipFilePath) || StringUtils.isEmpty(folderPath)) {
+			return;
+		}
+		File file = new File(zipFilePath);
+		if (!file.exists()) {
+			throw new ReportException("压缩包不存在:" + zipFilePath);
+		}
+
+		File folder = new File(folderPath);
+		if (!folder.exists()) {
+			folder.mkdirs();
+		}
+		if (!folder.isDirectory()) {
+			throw new ReportException("并非文件夹:" + folderPath);
+		}
+
+		try {
+			ZipFile zipFile = new ZipFile(file);
+			Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
+			while (zipEntries.hasMoreElements()) {
+				ZipEntry zipEntry = zipEntries.nextElement();
+				logger.info("unzip... " + zipEntry.getName());
+				InputStream inputStream = zipFile.getInputStream(zipEntry);
+				File outFile = new File(folder.getPath() + File.separator + zipEntry.getName());
+				if (!outFile.getParentFile().exists()) {
+					outFile.getParentFile().mkdirs();
+				}
+				OutputStream outputStream = new FileOutputStream(
+						folder.getPath() + File.separator + zipEntry.getName());
+				int b;
+				while ((b = inputStream.read()) != -1) {
+					outputStream.write(b);
+				}
+				inputStream.close();
+				outputStream.close();
+			}
+			zipFile.close();
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+		logger.info("unzip completed");
+	}
+}

+ 12 - 3
src/main/webapp/WEB-INF/views/fileUpload.html

@@ -3,14 +3,23 @@
 <head>
 <head>
 <meta charset="UTF-8">
 <meta charset="UTF-8">
 <title>文件上传</title>
 <title>文件上传</title>
-
+<link rel="stylesheet" href="static/css/fileUpload.css">
+<link rel="stylesheet"
+	href="static/lib/fontawesome/css/font-awesome.min.css">
 </head>
 </head>
 <body>
 <body>
 	<form method="post" enctype="multipart/form-data">
 	<form method="post" enctype="multipart/form-data">
-		选择要上传的文件<br /> <br /> <input id="file" type="file" name="file" /><br />
+		选择要上传的文件<br /> <br /> <input id="file" type="file" name="file" /><br />
 		<br />
 		<br />
 	</form>
 	</form>
-	<input id="upload" type="button" value="Upload" />
+	<p>上传类型</p>
+	<select id="typeSelect">
+		<option value="jrxml" selected="selected">jrxml模板</option>
+		<option value="zip">zip模板压缩包</option>
+		<option value="image">图片</option>
+		<option value="other">其他</option>
+	</select>
+	<button id="upload">上传</button>
 	<br />
 	<br />
 	<div id="progressDiv" hidden="true">
 	<div id="progressDiv" hidden="true">
 		<br /> 上传进度:
 		<br /> 上传进度:

+ 21 - 4
src/main/webapp/resources/js/upload/app.js

@@ -23,13 +23,30 @@ function upload() {
 		$("#result").html("文件为空,无法进行上传!");
 		$("#result").html("文件为空,无法进行上传!");
 		return;
 		return;
 	}
 	}
+	// 清除内容
+	$("#result").html("");
+	var fileType = document.getElementById("typeSelect").value || "jrxml";
+	var ext = value.substring(value.lastIndexOf(".") + 1);
+	if (fileType == "jrxml" || fileType == "zip") {
+		if (fileType != ext) {
+			$('#progressDiv').css("display", "hidden");
+			$("#result").html("文件并非" + fileType);
+			return;
+		}
+	} else if (fileType == "image") {
+		if (!/^(gif|jpg|jpeg|png|bmp|tiff|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw)$/
+				.test(ext)) {
+			$('#progressDiv').css("display", "hidden");
+			$("#result").html("文件并非图片");
+			return;
+		}
+	}
+
 	// 创建FormData对象,初始化为form表单中的数据
 	// 创建FormData对象,初始化为form表单中的数据
 	var formData = new FormData($('form')[0]);
 	var formData = new FormData($('form')[0]);
-	var userName = getParameter("userName");
-	if (userName == null || userName == "") {
-		userName = "UAS";
-	}
+	var userName = getParameter("userName") || "UAS";
 	formData.append('userName', userName);
 	formData.append('userName', userName);
+	formData.append('fileType', fileType);
 
 
 	// 显示进度
 	// 显示进度
 	$('#progressDiv').css("display", "block");
 	$('#progressDiv').css("display", "block");