您的位置:首页 >> 编程开发 >> Java >> JavaBeans >> 正文
RSS
 

老话题,JavaBean实现多文件上传

http://www.rdxx.com 04年12月20日 12:12 Blog 我要投稿

关键词: 文件上传 , JavaBean , 文件 , BEA , Java , 上传

在网上看到许多上传文件的例子,可是都是jsp程序,每遇到需要文件上传的地方就要复制这段上传代码并做相应修改,维护起来极不方便。为了增强代码的可重用性,我将这段通用的上传程序写成了JavaBean,请大家多提意见。

首先, 下载 commons-fileupload-1.0.zip 和 commons-beanutils-1.7.0.zip,

http://image.chinaitpower.com/files/20041220/13113.zip
http://image.chinaitpower.com/files/20041220/13117.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.*;

public class 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;
  }  
}

共2页  1 2

 
 
标签: 文件上传 , JavaBean , 文件 , BEA , Java , 上传 打印本文
 
 
  热点搜索
 
 
 



Valid XHTML 1.0 Transitional
Copyright ©2005 - 2008 Rdxx.Com,All Rights Reserved
收藏本页
收藏本站