⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 uploadbean.java

📁 《jsp网站开发技术》中的源代码(清华大学出版社)
💻 JAVA
字号:
package com.javacat.jsp.beans.upload;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
/**
*The UploadBean can be sued to transport a file from the client to
*the server.
*/
public class UploadBean
{
	ServletRequest request;
	ServletInputStream input;
	String objectDir="uploadDir";
	private int m_currentIndex;
	private int MAX_FILE_SIZE=1024*1024;//MAX FILE SIZE IS 1M bytes
	private byte[] m_binaries;
  private String m_boundary;//boundary of defferent data
  private int contentLength;
	/**
	*constructs a simple UploadBean
	*/
	public UploadBean()
	{
		super();
		m_currentIndex=0;
	}
	/**
	*constructs a UploadBean with the specified request
	*/
	public UploadBean(ServletRequest request)
	{
		this();
		this.setRequest(request);
	}
	/**
	*set the request of this bean
	*@param request the ServletRequest object to be set
	*/
	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());}
		}
	}
	/**
	*get the request of this bean
	*@return the request
	*/
	public ServletRequest getRequest()
	{
		return this.request;
	}
	/**
	*set the ServletInputStream of this bean.Bean will get data from this inputStream.
	*@param inputStream the ServletInputStream to be set
	*/
	public void setInputStream(ServletInputStream inputStream)
	{
		this.input=inputStream;
	}
	/**
	*get the InputStream of this servlet
	*/
	public ServletInputStream getInputStream()
	{
		return this.input;
	}
	/**
	*get the output stream to write the bytes that have been uploaded
	*for the specified file name.
	*@param filename the file name that can used to modify the output stream
	*@return the output stream to output the bytes
	*/
	public OutputStream getOutputStream(String filename)throws IOException
	{
    File file=new File(getObjectDir(),filename);
	  return new FileOutputStream(file);
	}
	/**
	*set the object directory to save upload files.
	*@param dir the object directory
	*/
	public void setObjectDir(String dir)
	{
		this.objectDir=dir;
	}
	/**
	*get the object directory to save upload files.
	*@return the object directory
	*/
	public String getObjectDir()
	{
		return this.objectDir;
	}

	/**
	*upload the file from the client
	*/
	public int upload() throws IOException,SecurityException
	{
    if(request==null)
      return -2;
    //local variables
    boolean isFile;
    String dataHeader;
    String fileName="";
    byte[] theBytes;
	int countFile=0;
	OutputStream output;
	
    contentLength = request.getContentLength();
    m_binaries = new byte[contentLength];
    int haveRead=0;
    //read all bytes
    while(haveRead<contentLength){
      haveRead+=getInputStream().read(m_binaries, haveRead, contentLength-haveRead);
    }
    boolean match=false;
    //find out the boundary
    m_boundary=new String();
    for(; !match && m_currentIndex < contentLength; m_currentIndex++)
    {
      if(m_binaries[m_currentIndex] == '\r')
        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;
      if(isFile)
      {
      	 fileName="";
      	 //if the file input field set nothing 
      	 //do not save this file
      	 if(!getFilePath(dataHeader).equals(""))
                fileName = getFileName(getFilePath(dataHeader));
         if((fileName==null)||(fileName.equals("")))
        	isFile=false;
      }
      theBytes=getDataSection();
      if(isFile)
      {
        if(theBytes.length>this.MAX_FILE_SIZE)
                    throw new SecurityException("File Size is too large.1M bytes is a limited");
        else{
          output=getOutputStream(fileName);
          output.write(theBytes);
          countFile++;
          output.close();
        }
      }
      if((char)m_binaries[m_currentIndex + 1] == '-')
                break;
      m_currentIndex = m_currentIndex + 2;
      } while(true);
	return countFile;
	}
	/**
	*get the DataSection of single file
	*@return an byte array contains the data
	*/
	private byte[] getDataSection()
	{
        int searchPosition = m_currentIndex;
        int keyPosition = 0;
        int boundaryLen = m_boundary.length();
        int start = m_currentIndex;//start of the data
        int end = m_currentIndex;//end of the data
        do
        {
            if(searchPosition >= contentLength)
                break;
            if(m_binaries[searchPosition] == (byte)m_boundary.charAt(keyPosition))
            {
                if(keyPosition == boundaryLen - 1)
                {
                    end = searchPosition - boundaryLen - 2;
                    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<data.length;i++)
        	data[i]=m_binaries[start+i];
        return data;
  }//get datasection
  /**
  *get data header of each data section
  */
  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++;
          }
        }
        return new String(m_binaries, start, (end - start) + 1);
    }
    /**
    *get file name from the file path name
    *@return the filename in the filepathname
    */
    private String getFileName(String filePathName)
    {
        int pos =-1;
        pos = filePathName.lastIndexOf('/')+1;//UNIX SYSTEM
        if(pos>0)
            return filePathName.substring(pos, filePathName.length());
        pos = filePathName.lastIndexOf('\\')+1;//WINDOWS SYSTEM
        if(pos>0)
            return filePathName.substring(pos, filePathName.length());
        else
            return filePathName;
    }
    /**
    *get file path from data  header
    *@return the filepath in the dataheader
    */
    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;
    }
    /**
    *set the max_file_size that the client can upload
    *@param maxValue the max value to be set
    */
    public void setMAXFILESIZE(int maxValue)
    {
    	if(maxValue>0)
    	this.MAX_FILE_SIZE=maxValue;
    }

}//~~~~~~~upload bean~~~~~~~~~~~~~~

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -