`
qq1988627
  • 浏览: 105885 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Struts2文件上传下载

 
阅读更多
package com.byd.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.tools.zip.ZipOutputStream;

import com.byd.core.BaseAction;
import com.byd.core.MyUtils;
import com.byd.Page;
import com.byd.bean.MyFile;

@SuppressWarnings("serial")
public class FileAction extends BaseAction {
	
	public static final String ROOT = "root\\";
	
	private File myUpload;

	private String myUploadContentType;

	private String myUploadFileName;

	private String path;

	private String node;

	private List nodes;

	private Page page;

	private String name;

	private String[] paths;

	private boolean success;

	/**
	 * 处理中文下载名
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public String getDownloadFileName() throws UnsupportedEncodingException {
		String named = new String(name.getBytes("ISO8859-1"),"utf-8" );
		return named;
	}

	/**
	 * 获得文件下载流
	 * 
	 * @return
	 * @throws FileNotFoundException
	 */
	public InputStream getInputStream() throws FileNotFoundException {
		try{
			return getServletContext().getResourceAsStream(ROOT + path + "/" + getDownloadFileName());
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}

	/**
	 * 下载文件
	 * 
	 * @return
	 */
	public String download() {
		return SUCCESS;
	}

	/**
	 * 解压缩文件
	 * 
	 * @return
	 */
	public String decompressionFiles() {
		String rootPath = getSession().getServletContext().getRealPath("/");
		rootPath += ROOT;
		File file = new File(rootPath);
		if(!file.exists()){
			file.mkdirs();
		}
		file = null;
		String extName, toPath, absPath;
		boolean flag = false;
		try {
			for (String path : paths) {
				file = new File(rootPath + path);
				if (file.isDirectory()) {
					continue;
				}
				extName = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
				toPath = rootPath + (((getPath() != null) && (getPath().length() > 0)) ? getPath().substring(1) : "")
						+ "\\";
				absPath = file.getAbsolutePath();
				if ("zip".equals(extName)) {
					flag = MyUtils.decompressionZipFiles(absPath, toPath);
				} else if ("rar".equals(extName)) {
					flag = MyUtils.decompressionRarFiles(absPath, toPath);
				}
			}
		} catch (RuntimeException e) {
			flag = false;
			e.printStackTrace();
		} finally {
			file = null;
		}
		setSuccess(flag);
		return SUCCESS;
	}

	/**
	 * 多文件下载
	 * 
	 * @throws IOException
	 */
	public String downloadAll() throws IOException {
//		String rootPath = getSession().getServletContext().getRealPath("/");
		return SUCCESS;
	}

//	public InputStream getZipInputStrean() throws IOException {
//		String rootPath = getSession().getServletContext().getRealPath("/");
//		ZipOutputStream zosm = null;
//		FileOutputStream fosm = null;
//		File file = null;
//		String zipName = "Untitled.zip";
//		
//		fosm = new FileOutputStream(rootPath + getPath() + "\\" + zipName);
//		zosm = new ZipOutputStream(fosm);
//		for (String path : paths) {
//			file = new File(rootPath + path);
//			MyUtils.compressionFiles(zosm, file, getPath());
//			file = null;
//		}
//		return MyUtils.getZipInputStrean(zosm, file, getPath());
//	}

	/**
	 * 多文件压缩
	 * 
	 * @return
	 * @throws IOException
	 */
	public String compressionFiles() throws IOException {
		String rootPath = getSession().getServletContext().getRealPath("/");
		rootPath += ROOT;
		File filed = new File(rootPath);
		if(!filed.exists()){
			filed.mkdirs();
		}
		filed = null;
		ZipOutputStream zosm = null;
		FileOutputStream fosm = null;
		File file = null;
		try {
			String zipName = "Untitled.zip";
			if (getPaths().length > 0) {
				String tempName = getPaths()[0];
				int start = tempName.lastIndexOf("\\");
				if (start != -1) {
					tempName = tempName.substring(start + 1);
				}
				zipName = tempName + ".zip";
				zipName = MyUtils.checkFileName(zipName, rootPath + getPath() + "\\");
			}
			fosm = new FileOutputStream(rootPath + getPath() + "\\" + zipName);
			zosm = new ZipOutputStream(fosm);
			for (String path : paths) {
				file = new File(rootPath + path);
				MyUtils.compressionFiles(zosm, file, getPath());
				file = null;
			}
			setSuccess(true);
		} catch (IOException e) {
			setSuccess(false);
			e.printStackTrace();
			throw e;
		} finally {
			file = null;
			if (zosm != null) {
				zosm.close();
			}
			if (fosm != null) {
				fosm.close();
			}
		}
		return SUCCESS;
	}
	/**
	 * 多文件删除
	 * 
	 * @return
	 */
	public String deleteFiles() {
		String rootPath = getSession().getServletContext().getRealPath("/");
		rootPath += ROOT;
		File file = new File(rootPath);
		if(!file.exists()){
			file.mkdirs();
		}
		file = null;
		boolean flag = false;
		try {
			for (String path : paths) {
				file = new File(rootPath + path);
				flag = MyUtils.delFiles(file);
				if (!flag) {
					break;
				}
			}
		} catch (RuntimeException e) {
			flag = false;
			e.printStackTrace();
		} finally {
			file = null;
		}
		setSuccess(flag);
		return SUCCESS;
	}

	/**
	 * 创建文件夹
	 * 
	 * @return
	 */
	public String createFolder() {
		String rootPath = getSession().getServletContext().getRealPath("/");
		rootPath += ROOT;
		String createPath = rootPath + getPath() + "/";
		setSuccess(MyUtils.mkDirectory(createPath + getName()));
		return SUCCESS;
	}

	/**
	 * 上传文件
	 * 
	 * @return
	 */
	public String uploadFiles() {
		String rootPath = getSession().getServletContext().getRealPath("/");
		rootPath += ROOT;
		String sp = rootPath + getPath();
		MyUtils.mkDirectory(sp);
		setSuccess(MyUtils.upload(getMyUploadFileName(), sp, getMyUpload()));
		return SUCCESS;
	}

	/**
	 * 2008-12-18-下午02:00:17
	 * 
	 * 功能:获得指定目录下的所有目录信息
	 * 
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	@SuppressWarnings("unchecked")
	public String getDirectories() throws FileNotFoundException, IOException {
		String rootPath = getSession().getServletContext().getRealPath("/");
		rootPath += ROOT;
		File file = new File(rootPath);
		if(!file.exists()){
			file.mkdirs();
		}
		file = null;
		nodes = listFiles(rootPath, node, true);
		return SUCCESS;
	}

	/**
	 * 2008-12-18-下午04:52:19
	 * 
	 * 功能:获得指定路径下大所有文件和文件夹信息,把数据封装到nodes返回
	 * 
	 * @param folder
	 *            当前要访问的文件夹目录名称
	 * @param onlyDirectory
	 *            null:获得所有信息,true:只获得文件夹,false:只获得文件信息
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	@SuppressWarnings("unchecked")
	private List listFiles(String rootPath, String folder, boolean onlyDirectory) throws FileNotFoundException,
			IOException {
		List filelist = new ArrayList();
		File[] arrFiles = new File(rootPath + folder).listFiles();
		MyFile nd = null;
		if (arrFiles != null) {
			for (File f : arrFiles) {
				String id = f.getAbsolutePath();
				nd = new MyFile();
				nd.setId(id.substring(rootPath.length()));
				nd.setText(f.getName());
				nd.setLeaf(f.isFile());
				nd.setFileName(f.getName());
				if (f.isFile()) {
					int size = new FileInputStream(f).available();
					if (size > 1024) {
						nd.setFileSize((size / 1000f) + " KB");
					} else {
						nd.setFileSize(size + " bytes");
					}
				} else {
					nd.setFileSize("0 bytes");
				}
				nd.setLastModifyDate(new Date(f.lastModified()));
				if (onlyDirectory && !f.isDirectory()) {
					continue;
				}
				filelist.add(nd);
			}
		}
		return filelist;
	}

	/**
	 * 2008-12-18-下午05:17:38
	 * 
	 * 功能:获得指定文件夹下面的所有文件和文件夹信息
	 * 
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public String getFiles() throws FileNotFoundException, IOException {
		String rootPath = getSession().getServletContext().getRealPath("/");
		rootPath += ROOT;
		File file = new File(rootPath);
		if(!file.exists()){
			file.mkdirs();
		}
		file = null;
		page = new Page();
		node = node == null ? "" : node;
		page.setRoot(this.listFiles(rootPath, node, false));
		int length = new File(rootPath + node).list().length;
		page.setTotalProperty(length);
		return SUCCESS;
	}

	public String getNode() {
		return node;
	}

	public void setNode(String node) {
		this.node = node.equals("*") ? "" : node; // 处理根结点特殊id
	}

	public List getNodes() {
		return nodes;
	}

	public void setNodes(List files) {
		this.nodes = files;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) throws UnsupportedEncodingException {
		this.path = URLDecoder.decode(path, "UTF-8");
	}

	public File getMyUpload() {
		return myUpload;
	}

	public void setMyUpload(File myUpload) {
		this.myUpload = myUpload;
	}

	public String getMyUploadContentType() {
		return myUploadContentType;
	}

	public void setMyUploadContentType(String myUploadContentType) {
		this.myUploadContentType = myUploadContentType;
	}

	public String getMyUploadFileName() {
		return myUploadFileName;
	}

	public void setMyUploadFileName(String myUploadFileName) {
		this.myUploadFileName = myUploadFileName;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getName() {
		return name;
	}

	public void setName(String fileName) throws UnsupportedEncodingException {
		this.name = URLDecoder.decode(fileName, "UTF-8");
	}

	public String[] getPaths() {
		return paths;
	}

	public void setPaths(String[] names) {
		this.paths = names;
	}
}
 <include file="struts-default.xml" />
 <package name="simple" extends="struts-default">
  <action name="download" class="fileAction" method="download">
   <result name="success" type="stream">
    <param name="contentType">application/octet-stream;charset=ISO8859-1</param>
    <param name="inputName">inputStream</param>
    <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
    <param name="bufferSize">4096</param>
   </result>
  </action>
 </package>

 

分享到:
评论

相关推荐

    struts2文件上传下载源代码

    在Struts2中,文件上传和下载是常见的功能需求,特别是在处理用户交互和数据交换时。这篇博客文章提供的"struts2文件上传下载源代码"旨在帮助开发者理解和实现这些功能。 文件上传功能允许用户从他们的设备上传文件...

    struts2文件上传下载

    在这个特定的项目中,我们关注的是"struts2文件上传下载"的功能,这涉及到用户通过Web界面上传文件到服务器,以及从服务器下载文件到用户的设备。 文件上传是Web应用中的常见需求,例如用户可能需要提交图片、文档...

    struts2文件上传下载实例

    在“struts2文件上传下载实例”中,我们将探讨如何在Struts2框架下实现文件的上传和下载功能,这对于许多Web应用程序来说是必不可少的特性。 首先,`pom.xml`文件是Maven项目对象模型的配置文件,它定义了项目的...

    Struts2文件上传下载和表单重复提交问题

    综上所述,Struts2文件上传下载和表单重复提交涉及多个技术点,包括Struts2的配置、文件操作、HTTP响应头设置、安全性和异常处理。理解并熟练掌握这些知识点,对于构建健壮的Web应用程序至关重要。

    struts2文件上传下载(注解版)

    在本项目中,我们关注的是Struts2中的文件上传和下载功能,这些功能是Web开发中常见的需求,尤其在处理用户数据提交或提供资源下载时。下面将详细介绍这个“struts2文件上传下载(注解版)”项目的关键知识点。 1. ...

    struts2实现文件上传下载

    Struts2是一个强大的MVC(模型-视图-控制器)框架,广泛应用于Java ...以上就是使用Struts2框架实现文件上传下载的基本步骤和关键知识点。在实际开发中,可以根据项目需求进行调整和优化,确保功能的稳定性和安全性。

    struts2 文件上传下载

    在Struts2中,文件上传和下载是常见的功能,它们允许用户从服务器上下载文件或向服务器上传文件。理解并掌握这一部分的知识对于开发交互性强的Web应用至关重要。 ### 一、文件上传 1. **使用Struts2的FileUpload...

    第八章:struts2文件上传下载.ppt

    第八章:struts2文件上传下载.ppt

    Struts2文件上传下载 中文乱码

    在Struts2框架中,文件上传和下载是常见的功能需求,但处理中文文件名或内容时,可能会遇到中文乱码的问题。这个问题主要涉及到字符编码的处理,包括HTTP请求的编码、文件名的编码以及文件内容的编码。接下来,我们...

    struts2文件上传与下载

    在Struts2中,文件上传和下载是常见的功能需求,主要用于处理用户在Web表单中提交的文件,如图片、文档等。下面将详细介绍Struts2中文件上传和下载的实现方法。 ### 1. 文件上传 #### 1.1 配置Struts2 首先,我们...

    Struts2文件上传与下载

    Struts2是一个强大的Java web框架,它为开发者提供了丰富的功能,包括处理用户表单提交、进行文件上传和下载。在Web应用中,文件上传和下载是常见的需求,例如用户上传头像、下载文档等。Struts2通过其Action类和...

    struts2 文件上传

    Struts2 文件上传是Web开发中的一个重要功能,它允许用户通过网页上传文件到服务器。Struts2 是一个基于MVC(Model-View-Controller)设计模式的Java Web框架,提供了丰富的特性和强大的控制层功能,使得文件上传...

Global site tag (gtag.js) - Google Analytics