服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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

在网上看到许多上传文件的例子,可是都是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.*;

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

文件上传测试, 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>

扫描关注微信公众号