使用struts2默认提供的方式上传文件
?
Action中的属性和方法
?private File uploadZip;
?private String uploadZipContentType;
?private String uploadZipFileName;
?
?public String uploads() {
??try {
???String savePath = ServletActionContext.getRequest().getRealPath(
?????"/upload");
???InputStream inputStream = new FileInputStream(uploadZip);
???OutputStream outputStream = new FileOutputStream(savePath
?????+ "/up.zip");
???byte[] buffer = new byte[1024];
???int len;
???while ((len = inputStream.read(buffer)) > 0) {
????outputStream.write(buffer, 0, len);
???}
???userService.getZipFile(savePath + "/up.zip",savePath);
???return "suc";
??} catch (Exception e) {
???e.printStackTrace();
???return "index";
??}
?}
?
?
Service中的方法
?
public void getZipFile(String path, String savePath) throws Exception {
??ZipFile zipFile = new ZipFile(path);
??Enumeration entryEnum = zipFile.getEntries();
??if (null != entryEnum) {
???ZipEntry zipEntry = null;
???while (entryEnum.hasMoreElements()) {
????zipEntry = (ZipEntry) entryEnum.nextElement();
????// if (zipEntry.isDirectory()) {
????// savePath = savePath + File.separator + zipEntry.getName();
????// System.out.println(savePath);
????// continue;
????// }
????if (zipEntry.getSize() > 0) {
?????// 指定文件
?????File targetFile = buildFile(savePath + File.separator
???????+ zipEntry.getName(), false);
?????OutputStream os = new BufferedOutputStream(
???????new FileOutputStream(targetFile));
?????// 读取zip
?????InputStream is = zipFile.getInputStream(zipEntry);
?????byte[] buffer = new byte[4096];
?????int readLen = 0;
?????while ((readLen = is.read(buffer, 0, 4096)) >= 0) {
??????os.write(buffer, 0, readLen);
?????}
?????os.flush();
?????os.close();
????} else {
?????// 空目录
?????buildFile(savePath + File.separator + zipEntry.getName(),
???????true);
????}
???}
??}
?}
?/**
? * 如果文件所在路径不存在则生成路径
? *
? * @param fileName
? *??????????? 文件名 带路径
? * @param isDirectory
? *??????????? 是否为路径
? * @return
? */
?public File buildFile(String fileName, boolean isDirectory) {
??File target = new File(fileName);
??if (isDirectory) {
???target.mkdirs();
??} else {
???if (!target.getParentFile().exists()) {
????target.getParentFile().mkdirs();
????target = new File(target.getAbsolutePath());
???}
??}
??return target;
?}
?