用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组件实现动态文件向数据库上传,其中未对文件大小、类型加以限制。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Zhiyuan_Ma/article/details/53861243

百度webuploader上传文件组件案例分析和使用-web网站开发3

-
  • 1970年01月01日 08:00

图片的上传和预览(上传到oracle数据库)

注意: 1.数据库字段使用clob存储 2.实体类中使用byte数组存图片流 3.图片预览以流的形式输出 文件上传下载预览辅助类代码: package com.yuanxin.app.ap...
  • MissGeng
  • MissGeng
  • 2017-05-31 14:32:37
  • 532

上传多个文件到oracle数据库

/* * Created on 2005-9-27 * * TODO To change the template for this generated file go to * Window - P...
  • hxirui
  • hxirui
  • 2006-05-18 18:19:00
  • 2216

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

uploadfile组件是apache开发的用于文件上传的Java组件。笔者经过研究,终于实现了动态多文件向数据库上传,现将示例程序介绍如下:   1.组件:笔者使用的是commons-upload...
  • Zhiyuan_Ma
  • Zhiyuan_Ma
  • 2016-12-24 17:40:07
  • 338

Oracle 组件 系列 小结

Oracle 组件的信息可以通过v$option 和 dba_registry 查看: --查看v$option: V$OPTION displaysOracle Database options a...
  • tianlesoftware
  • tianlesoftware
  • 2012-03-10 16:01:29
  • 10880

Oracle数据库版本及组件检查

在诸多的性能测试项目中发现,很多的性能测试工程师技术局限性过大,只懂得做性能监控和脚本的东西,性能是一个涉及各个环节,是一个需要对架构的各个层面全面了解的技术职业,否则你不可能走的很远。我觉得性能测试...
  • tomorrow_is_better
  • tomorrow_is_better
  • 2017-06-05 10:58:18
  • 307

psql连接oracle,windows不安装oracle,使用oracle组件包连接

使用plsql连接数据库,一般需要安装oracle服务器或者客户端,因为连接oracle需要tns监听;安装客户端等,安装包较大,需要的时间也多,可以直接在本机存放需要的配置文件,再手工修改plsql...
  • u010195712
  • u010195712
  • 2017-07-20 11:19:20
  • 189

Oracle XDB 组件 重建 说明

一.    XDB 组件说明1.1 官网说明:XDB 全称XML DB,官网的说明如下:http://docs.oracle.com/cd/E11882_01/appdev.112/e23094/xd...
  • tianlesoftware
  • tianlesoftware
  • 2012-03-06 00:34:47
  • 16239

11g安装oracle text组件

因项目需要,所以要在原本只an
  • xionglang7
  • xionglang7
  • 2014-09-23 13:43:52
  • 2829

Oracle Text 组件 说明

一.OracleText 组件说明 在说明之前,我们先用如下SQL 查看一下DB中的组件:SQL> col comp_id for a15SQL> col version for a15SQL> co...
  • tianlesoftware
  • tianlesoftware
  • 2012-03-08 21:55:13
  • 6198
收藏助手
不良信息举报
您举报文章:用uploadfile组件实现动态文件上传到ORACLE数据库
举报原因:
原因补充:

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