我们在开发项目的时候,特别是B/S系统,经常会遇到要批量上传文件的需求,对此需求一般有如下几个解决方案(以B/S为例):
1. 在客户端提供文件上传接口,一次上传一个文件
2. 一次上传多个文件
3. 将需要上传的文件打包,一次上传到服务器,并自动解压到指定目录
1,2方法都有几个很明显的不足,用户工作量大,文件如果过大,在网络环境中,上传的效率低下,另外文件在不同的目录,是无法进行一次选择上传的.所以打包上传就成为了比较流行的批量文件上传的解决方案,下面就来一起讨论一下在java中如何实现:
主要功能需求:
a. 上传文件,将文件保存在服务器
b. 读取服务器上压缩文件,解压到指定目录
下面就这两个需求说说编码实现
上传: 使用了smartupload开源程序
1. IUpload.java - (上传接口,需要jsmartupload.jar包)
import java.io.IOException;import java.util.Hashtable;
import javax.servlet.ServletException;
import com.jspsmart.upload.File;import com.jspsmart.upload.Files;import com.jspsmart.upload.Request;public interface IUpload { //只能上传一个文件 public File getSingleUploadFile() throws MultiFileException, UploadFileIsMissingException;
//判断文件是否丢失 public boolean exists(File file);
//保存文件 public int save(String targetFileName, int arg1) throws ServletException, IOException;
//得到绝对保存路径 public String getAbsoluteSavePath();
//得到请求 public Request getRequest();
//得到文件 public Files getFiles();
//处理所有参数,处理页面提交的其他表单数据 public Hashtable dealAllPara() throws Exception;
//得到zip文件名,不含后缀 public String getFilenameNoExt() throws MultiFileException, UploadFileIsMissingException;}
2. SingleUpload.java (本例子特意说明了控制只上传一个文件)
import java.io.IOException;import java.util.Enumeration;import java.util.Hashtable;
import javax.servlet.ServletException;
import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;
import com.commonStrut.utils.FileUtils;import com.jspsmart.upload.File;import com.jspsmart.upload.Files;import com.jspsmart.upload.Request;import com.jspsmart.upload.SmartUpload;
public class SingleUpload implements IUpload {
private Log logger = LogFactory.getLog(SingleUpload.class);
private SmartUpload upload = null;
private Request request = null;
private String savePath = "";
public SingleUpload(SmartUpload upload) throws ServletException, IOException { logger.info("SingleUpload:call super(),successed!"); this.upload = upload; this.upload.upload(); this.request = upload.getRequest(); }
//只能上传一个文件 public File getSingleUploadFile() throws MultiFileException, UploadFileIsMissingException { //产生一个file对象 myFile Files files = upload.getFiles();
//必须传入而且只能传入一个文件 logger.info("|------upload file count:" + files.getCount()); if (files.getCount() == 1) { File myFile = upload.getFiles().getFile(0); logger.info("|------upload file path name:" + myFile.getFilePathName()); if (myFile.isMissing()) { throw new UploadFileIsMissingException("上传文件丢失!"); } return myFile; } else { throw new MultiFileException("必须上传,而且一次只能上传一个文件!"); } }
//判断文件是否丢失 public boolean exists(File file) { return !file.isMissing(); }
//保存文件,如果文件不存在,新建目录,文件,(MultiFileException 请自建)
public int save(String targetFilePath, int arg1) throws ServletException, IOException { try { if (logger.isInfoEnabled()) logger.info("|------save upload file to :" + targetFilePath); File uploadFile = getSingleUploadFile(); String fileName = uploadFile.getFileName(); this.savePath = targetFilePath + java.io.File.separator + fileName; //按绝对路径保存 FileUtils.createNewFile(savePath); uploadFile.saveAs(savePath, arg1); logger.info("upload file and save is sucessed......!"); return 1; } catch (MultiFileException e) { throw new IOException(e.getMessage()); } catch (UploadFileIsMissingException e) { throw new IOException(e.getMessage()); } }
public String getAbsoluteSavePath() { return savePath; }
public Hashtable dealAllPara() throws Exception { Hashtable hashtable = new Hashtable(); Enumeration e = request.getParameterNames();
while (e.hasMoreElements()) { String paraname = (String) e.nextElement(); String para = request.getParameter(paraname); if ((paraname != null) && (para != null)) { hashtable.put(paraname, para); } logger.info("UPLOAD/param:name=" + paraname + ",value=" + para); } logger.info("param length = " + hashtable.size()); return hashtable; }
public String getFilenameNoExt() throws MultiFileException, UploadFileIsMissingException { File file = getSingleUploadFile(); String fileName = file.getFileName(); return fileName.substring(0, fileName.lastIndexOf(".")); }
public Request getRequest() { return upload.getRequest(); }
public Files getFiles() { return upload.getFiles(); }}
调用上两个类就可以实现文件上传,下面讨论文件解压
1. 解压接口
package com.commonStrut.utils;
public interface IZipUtils { //File zipFile, String unzipDir public String unzip() throws Exception;}
2. 解压
package com.commonStrut.utils;
import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;
import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;
/** * @author 魏 剑 * */public class ZipUtils implements IZipUtils { private Log logger = LogFactory.getLog(ZipUtils.class);
private File zipFile;
private String unzipDir;
public ZipUtils(File zipFile, String unzipDir) { this.zipFile = zipFile; this.unzipDir = unzipDir; }
public String unzip() throws Exception { logger.info("zipFile path=" + zipFile.getPath()); ZipFile zf = new ZipFile(zipFile); Enumeration enu = zf.entries(); String result = "";
while (enu.hasMoreElements()) { ZipEntry entry = (ZipEntry) enu.nextElement(); String name = entry.getName();
//如果解压entry是目录,直接生成目录即可,不用写入,如果是文件,要讲文件写入 String path = unzipDir + name; result = result + path + "<br/>"; File file = new File(path); if (entry.isDirectory()) { file.mkdirs(); } else {
//建议使用如下方式创建 流,和读取字节,不然会有乱码(当然要根据具体环境来定),具体原因请听
//下回分解,呵呵 InputStream is = zf.getInputStream(entry); byte[] buf1 = new byte[1024]; int len;
if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } OutputStream out = new FileOutputStream(file); while ((len = is.read(buf1)) > 0) { String buf = new String(buf1, 0, len);
out.write(buf1, 0, len); } } } result ="文件解压成功,解压文件:<br/>" + result; logger.info("----------------unzip msg = "+result); return result; }}
为了实现提交后后台一次处理,需要将上传&解压桥接起来,也写了一个类,有兴趣的朋友可以参考,别打人啊!哎呀,马上就完了package com.commonStrut.utils.upload;
import java.io.File;import java.io.IOException;import java.util.Hashtable;
import javax.servlet.ServletException;
import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;
import com.commonStrut.utils.IZipUtils;import com.commonStrut.utils.ZipUtils;import com.jspsmart.upload.Files;import com.jspsmart.upload.Request;import com.jspsmart.upload.SmartUpload;
public class ZipUploadAndUnzip implements IZipUtils,IUpload{
private Log logger = LogFactory.getLog(ZipUploadAndUnzip.class); private IZipUtils ziputils = null; private String uploadTargetFileName = ""; private String unzipDir = ""; private SingleUpload upload = null; public ZipUploadAndUnzip(SingleUpload upload, String saveTargetFilePath, String unzipDir) throws ServletException, IOException { this.upload = upload; this.uploadTargetFileName = saveTargetFilePath; this.unzipDir = unzipDir; }
public String unzip() throws Exception{ //保存 upload.save(uploadTargetFileName,SmartUpload.SAVE_PHYSICAL); //得到保存后文件 String savePath = upload.getAbsoluteSavePath(); logger.info("-------------absolute save path = "+savePath); File file = new File(savePath); //解压 ziputils = new ZipUtils(file,unzipDir); return ziputils.unzip(); } public String getFilenameNoExt() throws MultiFileException, UploadFileIsMissingException { return upload.getFilenameNoExt(); }
public com.jspsmart.upload.File getSingleUploadFile() throws MultiFileException, UploadFileIsMissingException { return upload.getSingleUploadFile(); }
public boolean exists(com.jspsmart.upload.File file) { return upload.exists(file); }
public int save(String targetFileName, int arg1) throws ServletException, IOException { return upload.save(targetFileName,arg1); }
public String getAbsoluteSavePath() { return upload.getAbsoluteSavePath(); }
public Request getRequest() { return upload.getRequest(); }
public Files getFiles() { return upload.getFiles(); }
public Hashtable dealAllPara() throws Exception { return upload.dealAllPara(); }}
有朋友说了,你既然这么罗嗦了,干脆把如何调用的也给个例子吧,好好好,盛情难却啊
假如你是用 struts,可以在Action类如下调用
public class UploadAction extends Action{ public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception {
SmartUpload mySmartUpload = new SmartUpload(); mySmartUpload.initialize(this.getServlet().getServletConfig(), request, response); SingleUpload singleUpload = new SingleUpload(mySmartUpload);
//处理参数
Hashtable allPara = singleUpload.dealAllPara();
//文件上传保存路径,&解压后保存的目录,这里是定义在配置文件中,具体实现大家写罗
String saveTargetFilePath = InitConfiguration.getInstance() .getCONFIG("uploadPicDir"); String unzipDir = InitConfiguration.getInstance().getCONFIG( "unzipPicDir");
//upload and unzip......... String unzipMsg = uploadAndUnzip(bf, singleUpload, allPara, saveTargetFilePath, unzipDir, true);
}
}
好了,要吃饭了,写的不好请多多包涵.也请多多指教,可不许骂人哦