zoukankan      html  css  js  c++  java
  • 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>
    
  • 相关阅读:
    将博客搬至CSDN
    JAVA代码备注
    清空数据库SQL
    实战ASP.NET访问共享文件夹(含详细操作步骤)
    我希望我知道的七个JavaScript技巧 译(转)
    ASP.NET获取客户端网卡使用的MAC地址信息
    JS中offsetTop、clientTop、scrollTop、offsetTop各属性介绍
    JS屏幕距离参数
    jQuery插件开发精品教程,让你的jQuery提升一个台阶
    jQuery编程的最佳实践
  • 原文地址:https://www.cnblogs.com/qq1988627/p/6606888.html
Copyright © 2011-2022 走看看