<%@ page contentType="text/html; charset=gb2312"%> 简单实用的文件上传组件例子
网站公告:   ◆北天JAVA技术网热情为java爱好者服务,本网内容包括JAVA(JSP、servlet、EJB、webservice、j2ee、javabean、应用服务器、JavaScript),数据库(MYSQL、SQL Server、Sybase、Oracle、DB2、数据库综合知识),设计研究(设计模式、Struts、Spring、Hibernate、设计框架、设计综合知识),WEB2.0新技术(主要介绍AJAX),以及各种技术的入门、实例、例子等等,欢迎各位多来坐坐!◆  诚邀各位JAVA爱好者加盟!◆  本网站内容丰富,更新快,保证每周20篇以上!  
加入收藏
设为首页
联系站长
承接项目
  相关资源:网站首页 | 免费培训学院 | 技术论坛 | JAVA聊天室 | 作家专栏 | 开发工具 | 认证考试 | 会员俱乐部
  JAVA技术初学者园地 | jsp与servlet | javascript | Java源代码 | EJB | web service | 应用服务器 | JAVA综合知识
  设计研究设计模式 | 设计框架 | Struts | Spring | Hibernate | 开源项目 | 面向对象设计 | 设计综合知识
  数 据 库MYSQL | SQL Server | Sybase | Oracle | DB2 | Informix | Access | 数据库综合知识
  其他资源:AJAX新技术 | 网站开发 | ERP软件 | OA办公软件 | 商业智能BI | 开发综合知识 | 承接项目 | 项目试用

 
 
简单实用的文件上传组件例子
     发布者:北天 发布时间:2006-07-25

简单实用的文件上传组件例子。网上虽然很多文件上传组件,但使用起来比较困难,这是一个简单实用的文件上传组件例子,采用jsp调用javabean方式。
上传输入页uploadfile.jsp,代码如下
<HTML>
<HEAD>
<TITLE>北天JAVA技术网上传附件</TITLE>
<link rel="stylesheet" type="text/css" href="site.css">
</head>

<BODY bgColor=menu topmargin=15 leftmargin=15 >
<CENTER>
  <form action="uploadsave.jsp" enctype="multipart/form-data" method="post" name="uploadForm">
  <table width=100%>
    <tr>
      <td> <FIELDSET align=left>
        <LEGEND align=left>上传图片</LEGEND>
        <TABLE >
          <TR>
            <TD >选择附件:
              <input type="file" name="uploadFile"/>
              <br/>
             
            </td>
          </TR>
        </TABLE>
        </fieldset></td>
      <td width=80 align="center"><input type=submit value='   确定   '>
        <br> <input type=submit value='   取消   ' onclick="window.close();"></td>
    </tr>
  </table>
  </form>
</center>
</body>
</html>

上传保存页uploadsave.jsp,代码如下
<%@ page contentType="text/html;charset=gbk" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>
<%@ page import="gbase.tool.upload.*" %>
<%
UploadBean theUploadBean=new UploadBean();

//附件上传到应用目录下的upload下,注意:要先手工在应用目录下建好文件上传到的目录结构,如上传到应用目录下的upload,就要在应用目录下先建upload文件夹。
String newfilesavepath=application.getRealPath(File.separator+"upload");

//上传后的文件名(不带扩展名,扩展名UploadBean类自动取原上传文件名的扩展名)
SimpleDateFormat timeformat = new SimpleDateFormat("yyyyMMddHHmmss");
java.util.Date date = Calendar.getInstance().getTime();
String createdate = timeformat.format(date).toString();
String newFileName="newfile"+createdate;

//上传后的文件名(包括扩展名)
String returnFileName="";
 try{
   
   returnFileName=theUploadBean.uploadFile(request,newfilesavepath,newFileName);
  
     }
  catch(SecurityException e)
    {
    returnFileName="";
    System.out.println("file upload fail");;
    }
if (!returnFileName.equals("")){
%>
<HTML>
<HEAD>
<TITLE>上传成功</TITLE>
</head>
<BODY>
<CENTER>
  <table width=100%>
    <tr>
      <td align="center"><br/><br/>
       上传成功,上传后的文件名为:<%=returnFileName%>
       </td>
       <td valign="bottom"  align="center">
 <input name="" type="button" value="关闭" onClick="javascript:window.close();">
 
  </td>
    </tr>
   
  </table>
</center>
</body>
</html>
  
<% 
 }else{
%>
<%@ page contentType="text/html;charset=gbk" %>
<html>
<head>
<title>上传文件出错</title>
</head>
<body>
<table>
    <tbody>
      <tr>
        <td  align="center">上传文件出错</td>
        <td valign="bottom"  align="center">
 <input name="" type="button" value="关闭" onClick="javascript:window.close();">
 
  </td>
      </tr>
    </tbody>
  </table>
</table>

</body>
</html>
<%}%>

上传组件javabean,代码如下
Request类:
package gbase.tool.upload;
import java.util.Enumeration;
import java.util.Hashtable;
/**
 * UploadBean
 * create date(2004/02/25)
 * @author:xiantianyou
 */
public class Request {

        private Hashtable m_parameters;
        private int m_counter;

        Request() {
                m_parameters = new Hashtable();
                m_counter = 0;
        }

        protected void putParameter(String name, String value) {
                if (name == null) {
                        throw new IllegalArgumentException("The name of an element cannot be null.");
                }
                if (m_parameters.containsKey(name)) {
                        Hashtable values = (Hashtable) m_parameters.get(name);
                        values.put(new Integer(values.size()), value);
                } else {
                        Hashtable values = new Hashtable();
                        values.put(new Integer(0), value);
                        m_parameters.put(name, values);
                        m_counter++;
                }
        }


        public String getParameter(String name) {
                if (name == null) {
                        throw new IllegalArgumentException("Form's name is invalid or does not exist (1305).");
                }
                Hashtable values = (Hashtable) m_parameters.get(name);
                if (values == null) {
                        return null;
                } else {
                        return (String) values.get(new Integer(0));
                }
        }


        public Enumeration getParameterNames() {
                return m_parameters.keys();
        }


        public String[] getParameterValues(String name) {
                if (name == null) {
                        throw new IllegalArgumentException("Form's name is invalid or does not exist (1305).");
                }
                Hashtable values = (Hashtable) m_parameters.get(name);
                if (values == null) {
                        return null;
                }
                String strValues[] = new String[values.size()];
                for (int i = 0; i < values.size(); i++) {
                        strValues[i] = (String) values.get(new Integer(i));
                }

                return strValues;
        }
}

UploadBean类:
package gbase.tool.upload;

/**
 * UploadBean
 * create date(2004/02/25)
 * @author:xiantianyou
 */

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class UploadBean {
ServletRequest request;
ServletInputStream input;
String objectDir="C:/";
private int m_currentIndex;
private int MAX_FILE_SIZE=50*1024*1024;
private byte[] m_binaries;
private String m_boundary;
private int contentLength;
private String fileName="";
private String newfileName="";
private Request m_formRequest;
private int m_totalBytes;
private int m_startData;
private int m_endData;

public UploadBean(){
super();
m_currentIndex=0;
m_totalBytes = 0;
m_currentIndex = 0;
m_startData = 0;
m_endData = 0;
m_boundary = new String();
m_formRequest = new Request();
}

 

public UploadBean(ServletRequest request){
this();
this.setRequest(request);
}

public void setRequest(ServletRequest request){
if (request!=null){

this.request=request;
try{
this.setInputStream(request.getInputStream());
}catch(IOException ioe){
System.out.println("IOException occurred in com.javacat.jsp.beans.upload.UploadBean.setRequest:"+ioe.getMessage());
}
}
}

public Request getRequest(){
return m_formRequest;
}

public void setInputStream(ServletInputStream inputStream){
this.input=inputStream;
}

public ServletInputStream getInputStream(){
return this.input;
}

public OutputStream getOutputStream(String filename) throws IOException{
int findex=filename.lastIndexOf("\\");
File file=new File(getObjectDir(), filename.substring(findex+1));
this.fileName=filename.substring(findex+1);
return new FileOutputStream(file);
}

public void setObjectDir(String sdir){
File dir=new File(sdir);
if (!dir.exists()){
dir.mkdir();
}
this.objectDir=sdir;
}

public void setNewfileName(String newfile){
this.newfileName=newfile;
}

public String getObjectDir(){
return this.objectDir;
}

public String getFileName(){
return this.fileName;
}

public int upload(ServletRequest request) throws IOException,SecurityException{
this.setRequest(request);
return this.upload();
}

public int upload() throws IOException,SecurityException{
if(request==null)
return -2;
boolean isFile;
int readBytes = 0;
String fieldName = new String();
String dataHeader;
String contentType = new String();
String fileName="";
byte[] theBytes;
int countFile=0;
OutputStream output;
contentLength =request.getContentLength();

m_binaries=new byte[contentLength];
int haveRead=0;
for (; haveRead < contentLength; haveRead += readBytes) {

                                request.getInputStream();
                                readBytes =
                                        request.getInputStream().read(
                                                m_binaries,
                                                haveRead,
                                                contentLength - haveRead);

                }
boolean match=false;
m_boundary=new String();

for (; !match && m_currentIndex < contentLength; m_currentIndex++) {
                        if (m_binaries[m_currentIndex] == 13) {
                                match = true;
                        } else {
                                m_boundary = m_boundary + (char) m_binaries[m_currentIndex];
                        }
                }
if (m_currentIndex==1)
return -1;
m_currentIndex++;
do{
if(m_currentIndex>=contentLength)
break;
dataHeader=getDataHeader();
m_currentIndex=m_currentIndex+2;
isFile=dataHeader.indexOf("filename")>0;
fieldName = getDataFieldValue(dataHeader, "name");
if (isFile) {
fileName="";
contentType = getContentType(dataHeader);
if(!getFilePath(dataHeader).equals(""))
fileName=getFileName(getFilePath(dataHeader));
if((fileName==null)||(fileName.equals("")))
isFile=false;
}
 if(newfileName.equals(""))
  ;
 else
 fileName=newfileName;
theBytes=getDataSection();
if(isFile){
if(theBytes.length>this.MAX_FILE_SIZE)
throw new SecurityException("File Size is too large. bytes is a limited");
else{
output=getOutputStream(fileName);
output.write(theBytes);
countFile++;
output.close();
}
if (contentType.indexOf("application/x-macbinary") > 0) {
m_startData = m_startData + 128;
}
}
else {String value = new String(m_binaries, m_startData, (m_endData - m_startData) + 1);

                                m_formRequest.putParameter(fieldName, value);
                        }
if ((char)m_binaries[m_currentIndex+1]=='-')
break;
m_currentIndex=m_currentIndex+2;
}while(true);
return countFile;
}

private byte[] getDataSection(){
int searchPosition=m_currentIndex;
int keyPosition=0;
int boundaryLen=m_boundary.length();
int start=m_currentIndex;
m_startData = m_currentIndex;
m_endData = 0;
int end=m_currentIndex;
do{
if(searchPosition>=contentLength )
break;
if(m_binaries[searchPosition]==(byte)m_boundary.charAt(keyPosition)){
if(keyPosition==boundaryLen-1){
end=searchPosition - boundaryLen - 2;
m_endData=end;
break;
}
searchPosition++;
keyPosition++;
}
else{
searchPosition++;
keyPosition=0;
}
}while(true);
m_currentIndex=end+boundaryLen+3;
byte[] data=new byte[end-start+1];
for(int i=0; i <end-start+1;i++)
    data[i]=m_binaries[start+i];
return data;
}


private String getDataHeader(){
int start =m_currentIndex;
int end=0;
int len=0;
boolean match=false;
while(!match){
if(m_binaries[m_currentIndex]=='\r' && m_binaries[m_currentIndex+2]=='\r'){
match=true;
end=m_currentIndex-1;
m_currentIndex=m_currentIndex+2;
}
else{
m_currentIndex++;
}
}
//String value = new String(m_binArray, m_startData, (m_endData - m_startData) + 1);
return new String(m_binaries,start, (end- start )+1);
}

private String getFileName(String filePathName){
int pos=-1;
pos=filePathName.lastIndexOf('/')+1;
if(pos>0)
return filePathName.substring(pos, filePathName.length());
else
return filePathName;
}

private String getFilePath(String header){
int filenameStart=header.indexOf("filename=");
int ctypeIndex=header.indexOf("Content-Type");
String filename=header.substring(filenameStart, ctypeIndex);
if ((filename.indexOf('\"')+1)==filename.lastIndexOf('\"'))
filename="";
else filename=filename.substring(filename.indexOf('\"')+1,filename.lastIndexOf('\"'));
return filename;
}

public void setMAXFILESIZE(int maxValue){
if(maxValue>0)
this.MAX_FILE_SIZE=maxValue;
}

private String getDataFieldValue(String dataHeader, String fieldName) {
                String token = new String();
                String value = new String();
                int pos = 0;
                int i = 0;
                int start = 0;
                int end = 0;
                token =
                        String.valueOf(
                                (new StringBuffer(String.valueOf(fieldName))).append("=").append('"'));
                pos = dataHeader.indexOf(token);
                if (pos > 0) {
                        i = pos + token.length();
                        start = i;
                        token = "\"";
                        end = dataHeader.indexOf(token, i);
                        if (start > 0 && end > 0) {
                                value = dataHeader.substring(start, end);
                        }
                }
                return value;
        }
        private String getContentType(String dataHeader) {
                String token = new String();
                String value = new String();
                int start = 0;
                int end = 0;
                token = "Content-Type:";
                start = dataHeader.indexOf(token) + token.length();
                if (start != -1) {
                        end = dataHeader.length();
                        value = dataHeader.substring(start, end);
                }
                return value;
        }
public String uploadFile(ServletRequest request,String filesavepath,String newFileName) throws IOException,SecurityException{
          request.setCharacterEncoding("gbk");
          String returnFileName="";
          UploadBean uploader=new UploadBean();
          uploader.setObjectDir(filesavepath);
          int i=uploader.upload(request);
          if(i==1){
          try{
            String oldfilename = uploader.getFileName();
            int maxSize = oldfilename.length();
            int begin_location = oldfilename.lastIndexOf(".");
            String newfileext = oldfilename.substring(begin_location + 1, maxSize);
            String oldfile = filesavepath + "/" + oldfilename;

            String newfile = filesavepath + "/" + newFileName + "." + newfileext;
            File f = new File(oldfile);
            File dest = new File(newfile);

            if (dest.exists()) {
              dest.delete();
            }
            if (f.exists()) {
              boolean b = f.renameTo(dest);
              if (b == true)
                System.out.println("Ok");
              else
                System.out.println("Error");
            }
            returnFileName=newFileName+"."+newfileext;
          }
          catch(Exception ex){ returnFileName="";}
          }
          else
          {returnFileName="";}
          return returnFileName;
   }
}

实例演示

实例原代码下载

(转载文章请保留出处:北天JAVA技术网(www.java114.com))
 
更多精彩文章:
测试例子 jsp + javaBean + EJB + oracle
EJB开发概述
通过Struts应用MVC设计模型
Struts用标签库提高开发速度
Struts使用Tiles辅助开发
struts傻瓜式学习
 
最近评论:
        
回复:简单实用的文件上传组件例子
生产厂下设研发部和生产车间,产品由专业机构研发设计,并大量使用美国、日本、德国等发达国家的进口原材料,并与国内相关科研、院校保持密切的联系,使产品处于同行业先进水平。本厂生产销售的产品有:普通全钢防静电地板,PVC全钢防静电地板,陶瓷防静电地板,PVC不开裂全钢防静电地板,PVC直铺永久防静电地板。其他产品如下: 1.停车场地坪; 2.北京环氧树脂地板漆; 3.旋转门。 4.ntn轴承; 5.日本轴承; 6.瑞典skf轴承
        
回复:简单实用的文件上传组件例子
昆明会议接待,云南民族风情旅游网,为您提供昆明会议,昆明会议接待等资讯。额外还包括:云南旅游网是云南旅游信息网站,对云南旅游信息、云南旅游景点、云南旅游线路等都有详细丰富的介绍。来云南旅游网可参考其他网友游记、旅游攻略等信息,图文并茂,云南旅行社昆明旅游昆明旅行社、昆明旅行社协会会长单位。。
        
soreness the day after sex uv
http://one.nked.cn/h011.jpghttp://one.nked.cn/h023.jpghttp://one.nked.cn/h129.jpghttp://one.nked.cn/h141.jpg http://one.nked.cn/h157.jpghttp://one.nked.cn/h158.jpghttp://one.nked.cn/h062.jpghttp://one.nked.cn/h074.jpg http://one.nked.cn/h100.jpghttp://one.nked.cn/h121.jpghttp://one.nked.cn/h161.jpghttp://one.nked.cn/h162.jpg http://one.nked.cn/h165.jpghttp://one.nked.cn/h166.jpghttp://one.nked.cn/h047.jpghttp://one.nked.cn/h057.jpg http://one.nked.cn/h192.jpghttp://one.nked.cn/h195.jpghttp://one.nked.cn/h035.jpghttp://one.nked.cn/h041.jpg baby namees baby namees mikaa mikaa thubzilla thubzilla ree english course ree english course aked women aked women nal nal mirthala salinas mirthala salinas madnna madnna carmen eectra carmen eectra mil hunter mil hunter emmma watson emmma watson subllime directory subllime directory pichunter.comm pichunter.comm sytem of a down sytem of a down map quesst map quesst vaness hudgens nude vaness hudgens nude girlls girlls arget arget simpsos porn simpsos porn amy olumbo amy olumbo fergiie fergiie sttrip sttrip aol maail aol maail www.googgle.com www.googgle.com disey porn disey porn crankthat crankthat sex video sex video tommys bookmrks tommys bookmrks search engine opttimization search engine opttimization slpknot slpknot nude womn nude womn breakng news breakng news mily cyrus mily cyrus cotact cotact tiiava tiiava thhehun thhehun short haiircut short haiircut play arcae games play arcae games www.myspce.com www.myspce.com oral sx oral sx gospel music lyris gospel music lyris bangbros..com bangbros..com jenna hazee jenna hazee xnxx..com xnxx..com site:http:/http: site:http:/http: gaysex gaysex slipkot slipkot wikkipedia wikkipedia anime orn anime orn driving dirctions driving dirctions tameka fostter tameka fostter paris hilton ex tape paris hilton ex tape asian pornn asian pornn my chemmical romance my chemmical romance freeons.com freeons.com amplannd amplannd freesex videos freesex videos ocal newspaper ocal newspaper www.899.com www.899.com lierotica.com lierotica.com hot sx hot sx womenn womenn justin imberlake justin imberlake clphunter clphunter yspace login yspace login freelady sonia freelady sonia beastiiality beastiiality 5 cent 5 cent search enngine search enngine helmsleys troubble helmsleys troubble cfnmm cfnmm addult friend finder addult friend finder lesbin lesbin ofice depot ofice depot big brther 8 big brther 8 breeasts breeasts nudst nudst ofice depot ofice depot free porn movies free porn movies hilaryy duff hilaryy duff playstaton2 game cheats playstaton2 game cheats play ggames play ggames batz games to play batz games to play sperm shack movis sperm shack movis loolita bbs loolita bbs expedi expedi playarcade games playarcade games squiirt squiirt music search by lrics music search by lrics paris hillton sex tape paris hillton sex tape sstaples sstaples kim kardashin kim kardashin girrls kissing girrls kissing aol maail aol maail ps ps beatiality beatiality niickelback niickelback literoica.com literoica.com lesian porn lesian porn all4a all4a Bye
        
回复:简单实用的文件上传组件例子
上海泰通阀门有限公司是一家集阀门、水泵、电机研发、制造、销售、服务与一体的综合性高新企业。 温州泰通阀门有限公司; 上海阀门厂; 调节阀; 减压阀; 闸阀; 蝶阀; 阀门网站地图
        
回复:简单实用的文件上传组件例子
新译通翻译公司成立于1997年,经过多年的发展,已经成为中国最具权威的专业翻译公司之一,专业提供英语翻译、日语翻译、德语翻译、法语翻译、俄语翻译、韩语翻译、意大利语翻译、葡萄牙语翻译、西班牙语翻译、阿拉伯语翻译等的大型翻译公司! ... 新译通上海翻译公司是知名品牌上海翻译公司,凭借我们团队的不断努力,已成为世界大型公司选择上海翻译公司的首选.北京翻译公司
        
回复:简单实用的文件上传组件例子
本公司是专业生产自吸泵的企业,我们所生产的自吸泵质量好,价格优,为您提供满意的自吸泵是我们最大的心愿; 水泵化工泵;江苏亚梅水泵业制造有限公司为中外合资企业,专业生产"亚梅"牌不锈钢耐腐蚀化工泵和非金属塑料合金泵。 压差旁通阀减压阀截止阀调节阀多功能水泵控制阀过滤器气动球阀气动蝶阀呼吸阀
        
free black porn movies
Absolutly free! http://7stc.cn/freepor1/free-porn-movie.html http://7stc.cn/freepor1/free-porn-movie-clip.html http://7stc.cn/freepor1/free-gay-porn-movie.html http://7stc.cn/freepor1/download-free-porn-movie.html http://7stc.cn/freepor1/free-porn-star-movie.html http://7stc.cn/freepor1/free-full-length-porn-movie.html http://7stc.cn/freepor1/free-full-porn-movie.html http://7stc.cn/freepor1/free-black-porn-movie.html http://7stc.cn/freepor1/free-teen-porn-movie.html http://7stc.cn/freepor1/free-homemade-porn-movie.html free porn movie free porn movie clip free gay porn movie download free porn movie free porn star movie free full length porn movie free full porn movie free black porn movie free teen porn movie free homemade porn movie free porn movie free porn movie clip free gay porn movie download free porn movie free porn star movie free full length porn movie free full porn movie free black porn movie free teen porn movie free homemade porn movie
        
回复:简单实用的文件上传组件例子
自吸泵化工泵管道泵离心泵齿轮泵; 江苏亚梅水泵业制造有限公司为中外合资企业,专业生产"亚梅"牌不锈钢耐腐蚀化工泵和非金属塑料合金泵。
        
~{;X84#:
~{7G3#:C~},~{P;P;~}
        
回复:简单实用的文件上传组件例子
谢谢!
        
标 题:   
内 容:   
 
                                  
 
免责声明:该文章由网友发表,如果对您造成侵权,请联系站长

首页 - 承接项目 - 网站地图 - 联系我们 -
版权所有北天JAVA技术工作室 ICP证号:粤ICP备06079815号