用uploadfile组件实现动态文件上传到ORACLE数据库

原创 2016年12月24日 17:40:07

uploadfile组件是apache开发的用于文件上传的Java组件。笔者经过研究,终于实现了动态多文件向数据库上传,现将示例程序介绍如下:

  1.组件:笔者使用的是commons-upload-1.2.jar和commons-io-1.3.2.jar,下载后将这两个jar包复制到WEBROOT/WEB-INF/lib下。

  2.JSP文件:

  <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<script type="text/JavaScript">
        var attachname = "attach";
        var i=1;
          function   addInput(){
            if(i>0){
                  var attach = attachname + i ;
                  if(createInput(attach))
                      i=i+1;
              }
              
          } 
          function deleteInput(){
     window.alert(i);
                  if(i>1){
                    i=i-1;
       if(!removeInput())
                        i=i+1;
                }
          } 
          
          function createInput(nm){   
              var  aElement=document.createElement("input");   
             aElement.name=nm;
             aElement.id=nm;
             aElement.type="file";
             aElement.size="50";
    var obj = document.getElementById("upload");
    var r =obj.insertRow().insertCell();
    temp = "<input type = file name = nm size = 50> ";
    r.innerHTML+=temp; 
    return true;

              //aElement.value="thanks";   
             //aElement.onclick=Function("asdf()");  
             //  if(document.getElementById("upload").appendChild(aElement) == null)
             //         return false;
             //  return true;
          } 

          function removeInput(){
               var obj = document.getElementById("upload");
      //if(obj.rows.length == 1) return false;
      obj.deleteRow();
     return true;
                //if(aElement.removeChild(aElement.lastChild) == null)
                //    return false;
                //return true;   
          }  
          
</script>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'MyJsp.jsp' starting page</title>
    
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">    
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
  
  <body>

  <form action="servlet/testuploadimg" method="post" enctype="multipart/form-data">
    <p>
  <input type="button" name="button" value="添加附件" onclick="addInput()">
  <input type="button" name="button" value="删除附件" onclick="deleteInput()">
      </p>
    <table width="200" border="0" id="upload">
      <tr>
        <td><input type="file" name="attach0" size="50"></td>
      </tr>
    </table>
    <input type="submit" value="确认上传" name="submit">
    <p>&nbsp;</p>
  </form>

    
  </body>
</html>
3.servlet

package Model;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import voucher.basic.DBHelper;


public class testuploadimg extends HttpServlet {

 /**
  * Constructor of the object.
  */
 public testuploadimg() {
  super();
 }

 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  * 
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  boolean hasfile = true;
  int j = 11;
  String dd = "";
  String filename = "";
  InputStream filestream = null;
  String MySQL = "";
  DBHelper dbc = new DBHelper(); 
  DiskFileItemFactory factry = new DiskFileItemFactory();  //实例化磁盘工厂
  ServletFileUpload svrupload = new ServletFileUpload(factry);  //定义上传文件类
  svrupload.setSizeMax(200*1024);  //文件大小
  try {
   List fileList = svrupload.parseRequest(request);  //客户端获取文件集合
   Iterator fileitr = fileList.iterator(); //获取fileList指针
   while(fileitr.hasNext()){  //遍历集合fileList
    FileItem fileitem = null; //设置FILEITEM对象
    String path = null; //保存文件所在路径
    long filesize = 0;  //保存文件长度
    fileitem = (FileItem)fileitr.next();  //取得FileItem对象
    if(fileitem == null || fileitem.isFormField()){ //对象为空或不是文件域
     continue; //循环查找下一个FILEITEM对象
    }    
    path = fileitem.getName(); //获取包括全路径的文件名
    filesize = fileitem.getSize(); //获取文件长度
    if(path.equals("")||filesize == 0){  //无上传文件返回
     hasfile = false;
     return;
    }
    filename = path.substring(path.lastIndexOf("//") + 1); //取得文件名
    filestream = fileitem.getInputStream();  //获取文件输入流对象
    
//实现文件上传代码成功    
//    filename = request.getRealPath("/") +"/"+ "filename1.gif";
//    FileOutputStream fos = new FileOutputStream(filename);
//    byte[] buffer = new byte[(int) filesize];
//    int count = 0;
//    while((count = filestream.read(buffer))>0){
//     fos.write(buffer, 0, count);
//     
//    }
//    fos.close();
//    filestream.close();
    
//将文件上传至数据库  
    
    //byte[] imgdata = new byte[(int)filesize];
    Connection dbcon = dbc.openDataBase();
    mySql = "insert into TESTIMG(IMGID,IMG) values(?,?)";
    try {
     
     PreparedStatement stat = dbcon.prepareStatement(mySql);
     dd = Integer.toString(j);
     stat.setString(1, dd);
     j++;
     stat.setBinaryStream(2, filestream, (int)filesize);
     stat.executeUpdate();
     stat.close();
     dbcon.close();
    } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   
  
  } catch (FileUploadException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out
    .println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.01 Transitional//EN/">");
  out.println("<HTML>");
  out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  out.println("  <BODY>");
  out.print("    This is ");
  out.print(this.getClass());
  out.println(", using the POST method");
  out.println("  </BODY>");
  out.println("</HTML>");
  out.flush();
  out.close();
 }

 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
 }

}

 

本示例程序只是说明如何使用uploadfiles组件实现动态文件向数据库上传,其中未对文件大小、类型加以限制。

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Uploadfile 文件上传控件使用方法

先在Page_Load方法添加点击事件 protected void Page_Load(object sender, EventArgs e) { btnU...

自定义标签的开发之tld文件

自定义标签的开发步骤:定义一个标签处理类;定义描述文件;根据描述文件处理标签       定义描述文件的过程:在WEB-INF下创建一个tld文件,复制apache-tomcat-7.0.22\we...

uploadFile文件上传

  • 2017年08月23日 11:12
  • 179KB
  • 下载

struts2--文件上传和uploadFile拦截器

单文件上传 1. 通过HTML表单上传文件时, 需要将表单的enctype属性设置为multipart/form-data, method属性设置为post.  jsp页面代码: ...

文件上传uploadfile he io

  • 2015年04月20日 16:22
  • 190KB
  • 下载

struts2--文件上传和uploadFile拦截器

单文件上传 1. 通过HTML表单上传文件时, 需要将表单的enctype属性设置为multipart/form-data, method属性设置为post.  jsp页面代码: ...

jsp 文件上传uploadfile

  • 2009年04月06日 20:45
  • 416KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:用uploadfile组件实现动态文件上传到ORACLE数据库
举报原因:
原因补充:

(最多只允许输入30个字)