jspsmartupload上传和其他的上传

代码如下!

一.jspsmartupload上传

1.上传部分

 /**
 *TigerOne's New Java Files
 *
 *Created on 2007-1-8
 * @author  TigerOne
 */
package com.tiger.control;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;

public class UpLoad {
 // 文件的保存路径
 private String SAVE_DIR_PATH;

 // 文件类型列表
 private String SAVE_FILE_TYPE;

 // 文件大小单位 bit
 private int SAVE_FILE_SIZE = 1024;

 public void setSAVE_DIR_PATH(String save_dir_path) {
  if (save_dir_path == null)
   save_dir_path = "//";
  else
   SAVE_DIR_PATH = save_dir_path;
 }

 public void setSAVE_FILE_TYPE(String save_file_type) {
  if (save_file_type == null)
   save_file_type = "";
  else
   SAVE_FILE_TYPE = save_file_type;
 }

 public void setSAVE_FILE_SIZE(int save_file_size) {
  SAVE_FILE_SIZE = save_file_size;
 }

 public String saveFile(ServletConfig servletConfig,
   HttpServletRequest request, HttpServletResponse response) {
  final SmartUpload mySmartUpload = new SmartUpload();
  try {
   // SmartUpload之初始化,一定要初始化才可以使用
   mySmartUpload.initialize(servletConfig, request, response);
   // 上传文件
   // 设置文件上传的格式
   mySmartUpload.setAllowedFilesList(SAVE_FILE_TYPE);

   // 最大文件3 M
   mySmartUpload.setMaxFileSize(SAVE_FILE_SIZE);
   mySmartUpload.upload();

  } catch (final Exception e) {
   System.out.println("文件大小或者格式有问题");
  }

  // 取得所有文件信息
  File myFile;
  String allname = "nopic";
  // 产生1个File对象
  myFile = mySmartUpload.getFiles().getFile(0);
  // 如果文件存在,则把他存入指定位址
  if (!myFile.isMissing()) {
   final String Ext = myFile.getFileExt();
   final String filename = "" + (int) (Math.random() * 100000000)
     + (int) (Math.random() * 100000000);
   allname = filename + "." + Ext;
   try { // 文件另存为
    myFile
      .saveAs(SAVE_DIR_PATH + allname,
        SmartUpload.SAVE_VIRTUAL);

   } catch (final Exception ex) {
    System.out.println("抛出异常 error---" + ex.getMessage());
   }
  }
  return allname;
 }

}

2.实际的sevelet

 /**
 *TigerOne's New Java Files
 *
 *Created on 2007-1-8
 * @author  TigerOne
 */
package com.tiger.student;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.IOException;
import com.tiger.control.UpLoad;

public class StudentAddNew extends HttpServlet{

 /*
  * 版本号
  */
 private static final long serialVersionUID = -3338235894233902871L;

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
  //PrintWriter out = response.getWriter();
  //设置响应头字体编码
  response.setContentType("text/html;charset=utf-8");
  //设置请求头字体编码
  request.setCharacterEncoding("utf-8");
  //保存系统
  
  //ConnectionPool connectionPool = (ConnectionPool) request.getAttribute("connectionPool");
  
  UpLoad upLoad = new UpLoad();
  upLoad.setSAVE_FILE_TYPE("jpg,gif");
  upLoad.setSAVE_FILE_SIZE(400*1024);
  upLoad.setSAVE_DIR_PATH("//images_tt//");
  
  final ServletConfig servletConfig = getServletConfig();
  String filename = upLoad.saveFile(servletConfig, request, response);

//输出上传后的文件名
  System.out.println(filename);

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }
}

3.测试页面

<html>
<head>
<title>Jspsmart Example:File</title>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
</head>

<body bgcolor="#FFFFFF" text="#000000">
<p><font size="5" color="#FF0000"><b>JSPSMART 文件上传例子</b></font></p>
<form name="aaa"  method="post" action="StudentAddNew" enctype="multipart/form-data">
<p> 上传文件1:
<input type="file" name="File1" size="20" maxlength="20">
</p>
<p>上传文件1描述:
<input type="text" name="File1" size="30" maxlength="50">
</p>
<p>上传文件2:
<input type="file" name="File2" size="20" maxlength="20">
</p>
<p>上传文件2描述:
<input type="text" name="File2" size="30" maxlength="50">
</p>
<p>上传文件3:
<input type="file" name="File3" size="20" maxlength="20">
</p>
<p>上传文件3描述:
<input type="text" name="File3" size="30" maxlength="50">
</p>
<p>
<input type="submit" value="上传">
<input type="reset" value="清除">
</p>
</FORM>
</body>
</html>

4.web.xml配置

<servlet>
  <servlet-name>StudentAddNew</servlet-name>
  <servlet-class>com.tiger.student.StudentAddNew</servlet-class>
</servlet>

 <servlet-mapping>
    <servlet-name>StudentAddNew</servlet-name>
    <url-pattern>/StudentAddNew</url-pattern>
  </servlet-mapping>

 

二.另一个上传一个朋友在学生时代写的

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

/**
 * 文件、图片上传组件
 * @author newjay
 * @version 1.0
 */
public class Upload
{
 public Upload()
 {
  debug = false; b1 = false; b2 = false;
  separator = System.getProperty("file.separator");
  StringBuffer sb = new StringBuffer(separator);
  sb.append("images"); sb.append(separator);
  sb.append("usersPic");
  filePath = sb.toString();
  if(debug)
   System.err.println(filePath);
 }
 
 /**
  * 初始化组件参数
  * @param servletcontext   Initial ServletContext
  * @param httpservletrequest    Initial HttpServletRequest
  * @param httpservletresponse   Initial Httpservletresponse
 */
 public final void init(ServletContext servletcontext,
        HttpServletRequest httpservletrequest,
          HttpServletResponse httpservletresponse)
        throws ServletException
    {
        m_application = servletcontext;
  m_request = httpservletrequest;
        m_response = httpservletresponse;
    }

 /**
  * 初始化组件参数
  * @param pagecontext   Initial PageContext
 */
    public final void initialize(PageContext pagecontext)
        throws ServletException, UnsupportedEncodingException
    {
        m_application = pagecontext.getServletContext();
        m_request = (HttpServletRequest)pagecontext.getRequest();
        m_response = (HttpServletResponse)pagecontext.getResponse();
    }
 
 /**
  * 初始化组件参数
 */
    public final void initialize(ServletContext servletcontext,
       HttpSession httpsession, HttpServletRequest httpservletrequest,
         HttpServletResponse httpservletresponse, JspWriter jspwriter)
             throws ServletException
    {
        m_application = servletcontext;
  m_session = httpsession;
        m_request = httpservletrequest;
        m_response = httpservletresponse;
  m_out = jspwriter;
    }

 /**
  * 上传函数
  * @exception IOException
 */
 public void upload()throws IOException
 {
    if(!b1)
     filePath = m_application.getRealPath(filePath);
    if(debug)
    m_out.print("文件路径:" + filePath);
    String tempfilename=(String)m_request.getSession().getId();
          File f1 = new File(filePath,tempfilename);
          int n;
          try
          {
              InputStream in = m_request.getInputStream();
              BufferedInputStream my_in = new BufferedInputStream(in);
              FileOutputStream fout = new FileOutputStream(f1);
              BufferedOutputStream my_out = new BufferedOutputStream(fout);
              byte[] b = new byte[10000];
              while((n = my_in.read(b)) != -1)
              {
                   my_out.write(b,0,n);  //先把数据存入服务器临时文件
              }
              my_out.flush();
              my_out.close();
              fout.close();
              my_in.close();
              in.close();
     if(debug)
    m_out.print("<br>文件上传成功!<br>");
          }
          catch(IOException e)
          {
              m_out.print("文件上传失败!<br>");
          }
         
          try
          {  
              RandomAccessFile random1 = new RandomAccessFile(f1,"r");
              if(!b2)//取得原文件名
     {
      random1.readLine();
      fileName = random1.readLine();
      byte[] b = fileName.getBytes("ISO-8859-1");
      fileName = new String(b);
      //判断客户端的文件间隔符
      int pointer = fileName.lastIndexOf('//');
      if(pointer == -1)
       pointer = fileName.lastIndexOf('/');

      fileName = fileName.substring(pointer+1,fileName.length()-1);
     }
              File f2 = new File(filePath, fileName);
              RandomAccessFile random2 = new RandomAccessFile(f2,"rw");
              random1.seek(0);
              for(int i=1; i<=4; i++)//去掉前4行信息非文件信息
              {
                   String tempstr = random1.readLine();
              }
              long startPoint = random1.getFilePointer();
              random1.seek(random1.length());
              long mark = random1.getFilePointer();
              int j=0;
              long endPoint=0;
              while((mark>=0)&&(j<=6))//去掉最后6行非文件信息
              {
                   mark--;
                   random1.seek(mark);
                   n=random1.readByte();
                   if(n=='/n')
                   {
                         j++;
                         endPoint=random1.getFilePointer();
                   }
              }
     //分批存取将取得高的速度和性能
              long length = endPoint-startPoint+1;
              int order = (int)(length/10000);
              int left = (int)(length%10000);
              byte[] c = new byte[10000];
              random1.seek(startPoint);
              for(int i=0; i<order; i++)
              {
                    random1.read(c);
                    random2.write(c);
              }
              random1.read(c,0,left);
              random2.write(c,0,left);
              random1.close();
              random2.close();
              f1.delete();
     if(debug)
    m_out.print("文件更新成功!<br>");
          }
          catch(Exception e)
          {
              m_out.print("文件更新失败!<br>");
          }
 }

 public void setFileName(String str)
 { fileName = str; b2 = true; }

 public String getFileName()
 { return fileName; }

 public void setFilePath(String str)
 { filePath = str;  b1 = true; }

 /**
  * 取得文件路径
 */
 public String getFilePath()
 { return filePath; }

 /**
  * 是否显示调试信息
  * @param bl 显示调试参数
 */
 public void setDebug(boolean bl)
 { debug = bl; }

 protected HttpServletRequest m_request = null;
 protected HttpServletResponse m_response = null;
 protected ServletContext m_application = null;
 protected HttpSession m_session = null;
 protected JspWriter m_out = null;
 private String fileName = null;
 private String filePath = null;
 private String separator = null;
 private boolean debug;
 private boolean b1; //判断是否设置了新的文件路径
 private boolean b2; //判断是否设置了新的文件名
}

2.上传页面

<%@ page contentType="text/html;charset=gb2312" %><head>
<title>UploadBean 示例</title>
</head>
 
<FORM name="upload" METHOD="POST" ACTION="Upload.jsp" ENCTYPE="multipart/form-data">
<table><tr>
<td>上传文件路径:</td>
<td> <input name="attach" type="FILE" size="50" > </td>
</tr></table>
<input name="ok" type= "submit" value="提交">
</form>

3.处理页面

<%@ page contentType="text/html;charset=gb2312" %>
<html>
<body>
<jsp:useBean id="smartUpload" scope="page" class="newjay.SmartUpload" />
<%
smartUpload.initialize(application, session, request, response, out);
smartUpload.setFilePath("C://okok//");
//smartUpload.setFileName("over.mp3");
smartUpload.setMaxFileSize(6291456);

String exts[] = {"gif", "jpg", "mP3"};
smartUpload.setFileExts(exts);

switch(smartUpload.upload())
{
 case -1: out.print("<br><font size=3 color=red>文件上传失败!可能服务器繁忙,请呆会再试!</font><br>"); break;
 case 0: out.print("<br><font size=3 color=red>上传成功!</font><br>"); break;
 case 1: out.print("<br><font size=3 color=red>上传的文件大小超过要求的字节数!</font><br>"); break;
 case 2: out.print("<br><font size=3 color=red>文件上载到服务器失败!</font><br>"); break;
 case 3: out.print("<br><font size=3 color=red>禁止上传该类型的文件!</font><br>"); break;
}
%>
</body>
</html>           

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值