• 软件测试技术
  • 软件测试博客
  • 软件测试视频
  • 开源软件测试技术
  • 软件测试论坛
  • 软件测试沙龙
  • 软件测试资料下载
  • 软件测试杂志
  • 软件测试人才招聘
    暂时没有公告

字号: | 推荐给好友 上一篇 | 下一篇

简单实用的文件上传组件例子

发布: 2007-7-04 13:34 | 作者: admin | 来源:  网友评论 | 查看: 21次 | 进入软件测试论坛讨论

领测软件测试网

简单实用的文件上传组件例子。网上虽然很多文件上传组件,但使用起来比较困难,这是一个简单实用的文件上传组件例子,采用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;
   }
}

实例演示

实例原代码下载

延伸阅读

文章来源于领测软件测试网 https://www.ltesting.net/


关于领测软件测试网 | 领测软件测试网合作伙伴 | 广告服务 | 投稿指南 | 联系我们 | 网站地图 | 友情链接
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备2023014753号-2
技术支持和业务联系:info@testage.com.cn 电话:010-51297073

软件测试 | 领测国际ISTQBISTQB官网TMMiTMMi认证国际软件测试工程师认证领测软件测试网