JavaBean实现多文件上传

来源:互联网 发布:webmail java 开源 编辑:程序博客网 时间:2024/05/21 03:26
  转载
在网上看到许多上传文件的例子,可是都是jsp程序,每遇到需要文件上传的地方就要复制这段上传代码并做相应修改,维护起来极不方便。为了增强代码的可重用性,我将这段通用的上传程序写成了JavaBean,请大家多提意见。
首先, 下载 commons-fileupload-1.0.zip 和 commons-beanutils-1.7.0.zip,
http://apache.freelamp.com/jakarta/commons/fileupload/binaries/commons-fileupload-1.0.zip
http://apache.freelamp.com/jakarta/commons/beanutils/binaries/commons-beanutils-1.7.0.zip
解压缩得到 commons-fileupload-1.0-beta-1.jar 和commons-beanutils.jar, 并将两个包放到 "YourWebApp/WEB-INF/lib"文件夹下。
//UploadFile.java
package com.esurfer.common;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.text.SimpleDateFormat;
import java.io.*;
import org.apache.commons.fileupload.*;
publicclass UploadFile {
  
private String tmpdir;
  
private String updir;
  
private HttpServletRequest request;
 public HttpServletRequest getRequest() {
      
return request;
  }
   public void setRequest(HttpServletRequest request) {
      
this.request = request;
  }
  
public String getTmpdir() {
      
return tmpdir;
  }
   public void setTmpdir(String string) {
       tmpdir = string;
  } 
 
   
public String getUpdir() {
      
return updir;
  }
   public void setUpdir(String string) {
       updir = string;
  }
 
  
/**
    * Create directory with the name 'path'
    * @param path
    * @return
    */
 
  
private String MkDir(String path) {
       String msg = null;
       java.io.File dir;
       // Create new file object
       dir =
new java.io.File(path);
      
if (dir == null) {
           msg = "
Error:<BR>Can't create empty directory!";
          
return msg;
       }
      
if (dir.isFile()) {
           msg = "
Error:<BR>File name <B>" + dir.getAbsolutePath() +
                 "
</B> already exists!";
          
return msg;
       }
      
if (!dir.exists()) {
          
boolean result = dir.mkdirs();
          
if (result == false) {
               msg = "
Error:<BR>Create directory <b>" +
                     dir.getAbsolutePath() + "
</B> failed!";
              
return msg;
           }
          
return msg;
       } else {
       }
      
return msg;
  }
 
  
/**
    * Get current datetime used to name a file uploaded
    * @return
    */

  
private String getCurDateTime(){
       SimpleDateFormat df = new SimpleDateFormat("
yyMMddHHmmss");
      
return df.format(new Date());
  }
 
  
/**
    * Upload files
    * @return
    */

  
public String[] uploadFile() {
       String msg = "";
       String img = null;
  
      
// the final filename of the file uploaded
       String sFinalName = "";
  
       DiskFileUpload fu = new DiskFileUpload();
 
      
// maximum size in byte that permitted to upload
       fu.setSizeMax(51200);
 
      
// maximum size in byte that will be stored in memory
       fu.setSizeThreshold(4096);
 
      
// the tempory path that the file(s) will be stored
       // when greater than getSizeThreshold()
       fu.setRepositoryPath(tmpdir);
 
      
// begin read information of upload
       List fileItems = null;
      
try {
           fileItems = fu.parseRequest(request);
       }
catch (FileUploadException e) {
           System.err.println("Upload File Failed!");
      }
       // process each file uploaded
       Iterator iter = fileItems.iterator();
 
      
// root dir to store file uploaded
       String uproot = updir;
  
      
// ArrayList used to save uploaded file name
       ArrayList uploadedFiles = new ArrayList();
  
       String filepath = updir;
       String opmsg = MkDir(filepath);
      
if (opmsg == null) {
          
while (iter.hasNext()) {
               FileItem item = (FileItem) iter.next();
             
// Ignore the other type of form field(s) except file
               if (!item.isFormField()) {
                   String name = item.getName();
                   long size = item.getSize();
                  
if ((name == null || name.equals("")) && size == 0) {
                       continue;
                   }
                   name = name.replace('
//','/');
                   File fullFile = new File(name);

                  
// get the extension

                   String sExtension = fullFile.getName().substring(
                          fullFile.getName().lastIndexOf("."),
                          fullFile.getName().length());           
                  
// Generate the new filename
                   String sNewFileName = getCurDateTime() + sExtension;
         
                  
// Set the final filename to sNewFileName
                   sFinalName = sNewFileName;
     
                  
// Create the file with the generated name
                   File savedFile = new File(filepath, sNewFileName);
         
                  
// If the file already exist, assign a new name to it
                   for (int k = 0; savedFile.exists(); k++) {
                      
// get the file name from the variable
                       String sTmpFileName = sNewFileName;   
        
                      
// get the file name except the extension

                       String sFileName = sNewFileName.substring(0,
                                          sNewFileName.lastIndexOf("."));   
        
                      
// combine a new file name

                       savedFile = new File(filepath, sFileName + k + sExtension);    
         
                      
// get the new generated file name as the final filename
                       sFinalName = sFileName + k + sExtension;  
                   }
                  
try {
                       item.write(savedFile);
                   }
catch (Exception e1) {
                       System.err.println("Upload File Failed!");
                   }
                   uploadedFiles.add(sFinalName);
               }
           }
       }
       String sUploadedFileNames[] = new String[uploadedFiles.size()];
       uploadedFiles.toArray(sUploadedFileNames);
       return sUploadedFileNames;
     }  
 }
文件上传测试, fileupload.jsp
<%@ page pageEncoding="GBK"%>
<%@ page contentType="text/html;charset=GBK"%>
<jsp:useBean id="up" class="com.esurfer.common.UploadFile" scope="page"/>
<%
 String contextPath     = getServletContext().getRealPath("/");
 String uploadTmpPath   = (contextPath + "tmp").replace('//', '/');
 String uploadRootPath = (contextPath + "upload").replace('//', '/');
 String sAction = request.getParameter("operate");
 if (sAction == null) sAction = "";
 if (sAction.equals("upload")) {
     up.setTmpdir(uploadTmpPath);
     up.setUpdir(uploadRootPath);
     up.setRequest(request);
     String[] sUploadFileNames = up.uploadFile();
     for (int i = 0; i < sUploadFileNames.length ; i++ ) {
         out.println(sUploadFileNames[i]);
     }
 }
%>
<html>
<head>
<title>Upload</title>
</head>
<body>
<center>
<h1>Upload File Test</h1>
<form name="uploadform" method="POST" action="?operate=upload" 
      enctype="multipart/form-data">
 File 1:<input name="file1" size="40" type="file"><br />
 File 2:<input name="file2" size="40" type="file"><br />
 File 3:<input name="file3" size="40" type="file"><br />
 <input name="upload" type="submit" value="Upload" />
</form>
</center>
</body>
</html>