给个示例吧
String sql="insert into user values(?,?)";
PreparedStatement pstmt=con.prepareStatement(sql);File file=new File("..");
FileInputStream fin=new FileInputStream(file);pstmt.setString(1,"name");
pstmt.setBinaryStream(2,fin,(int)file.length());pstmt.executeUpdate();
pstmt.close();
fin.close();

解决方案 »

  1.   

    做过一个传至服务器的代码,你只要把其中的savefile方法重写,改成写到数据库就行了,你需要吗?
      

  2.   

    是的,请kmyhy(颐和园)兄帮忙,谢谢了
      

  3.   


    首先  import oracle.sql.BLOB;然后如下
    ---------------------------------------
    private void koubunshoInsert(DBAccessExt db, String system_id,
    String reception_id, String master_gid, String filename, File file,
    String contentType) throws Exception {
    ResultSet rs = null;
    StringBuffer sql = new StringBuffer(""); //新規登録
    sql.append(" INSERT INTO  EXT_DOCUMENT ");
    sql.append(" VALUES ( ");
    sql.append("'" + replaceSQLString(system_id) + "' , ");
    sql.append("'" + replaceSQLString(reception_id) + "' , ");
    sql.append("'" + replaceSQLString(master_gid) + "' , ");
    sql.append(" 1 , ");
    sql.append("'" + "' , ");
    sql.append(" EMPTY_BLOB() , ");
    sql.append("'" + "' , ");
    sql.append("'" + replaceSQLString(filename) + "' , ");
    sql.append(" EMPTY_BLOB() , ");
    sql.append("'" + replaceSQLString(contentType) + "' , ");
    sql.append(" EMPTY_BLOB() , ");
    sql.append(" 0 , ");
    sql.append("SYSDATE, ");
    sql.append("SYSDATE, ");
    sql.append("'" + "' , ");
    sql.append("'" + "' , ");
    sql.append("'" + "' , ");
    sql.append("'" + "'  ");
    sql.append(" ) ");
    db.insert(sql.toString()); // BLOB登録
    sql = new StringBuffer("");
    sql.append(" SELECT * FROM EXT_DOCUMENT ");
    sql
    .append(" WHERE EXT_SYSTEM_ID='" + replaceSQLString(system_id)
    + "'");
    sql
    .append(" AND RECEPTION_ID='" + replaceSQLString(reception_id)
    + "'");
    sql.append(" AND MASTER_GROUP_ID='" + replaceSQLString(master_gid)
    + "'");
    sql.append(" AND DOC_NUMBER=1"); rs = db.query(sql.toString()); if (rs.next()) {
    BLOB blob1 = (BLOB) rs.getBlob("OFF_FILE");
    BufferedOutputStream out1 = new BufferedOutputStream(blob1
    .getBinaryOutputStream());
    BufferedInputStream in1 = new BufferedInputStream(
    new FileInputStream(file));
    int buffer1;
    while ((buffer1 = in1.read()) != -1) {
    out1.write(buffer1);
    }
    out1.close();
    in1.close();
    }
    rs.close(); }
      

  4.   

    说明:
    1.这个页面需要一个表单页面将用户的文件提交到这个页面,以便服务器处理;
    2.connect.jsp是连接oracle的语句;
    3.本来也考虑到直接把文件写到数据库的,因为我们的主要应用中的数据库负担太大,后面改为把文件保存到服务器的两个目录下:upload(文档)和attach(附件),然后把文件目录信息记录在表中,方便检索和管理;
    4.为了方便你看,注释是我加上的.
    (connect.jsp<%@ page contentType="text/html;charset=gb2312"%>
    <%
    boolean bLogin=false;
    if((String)session.getAttribute("username")==null||((String)session.getAttribute("username")).equals(""))bLogin=false;
    else bLogin=true;
    if(bLogin=false){response.sendRedirect("login.jsp");}%>
    <html><head><title></title></head>
    <%@ include file="connect.jsp"%>
    <body>
    <%@ page import="java.util.Date,java.text.SimpleDateFormat,java.util.*,java.io.*" %>
    <%!
    String getCHS(String str){
    /*if(str==null)str="";
    String s=str;
    try{s=new String(str.getBytes("ISO-8859-1"), "GB2312");}
    catch(java.io.UnsupportedEncodingException e){}
    return s;*/
    return str;
    }
    %>
    <%!
    String fileName,fieldName,saveName;
    long start,end;
    Hashtable fields=new Hashtable();
    String getFieldValue(String fieldName){
    if(fields==null||fieldName==null)return null;
    return(String) fields.get(fieldName);
    }
    //把流保存到临时文件以便进一步处理
    void saveStreamData2tmpFile(InputStream in,File tmpFile){
    try{FileOutputStream o=new FileOutputStream(tmpFile);

    byte b[]=new byte
    [1024];
    int i; while((i=in.read(b))!=-1){o.write(b,0,i);}
    o.close();in.close();
    }catch(Exception e){/*必须捕捉FileNotFoundException和IOException*/
    System.out.println(e.getMessage());}
    }
    String getFieldName(String line){

    String str=line.substring(line.indexOf("name=\"")+6);
    String fieldName=str.substring(0,str.indexOf("\""));
    if(fieldName!=null)return fieldName;
    else return null;
    }
    String getFileName(String line){

    String str=line.substring(line.indexOf("filename=\"")+10);
    str=str.substring(0,str.indexOf("\""));
    String fileName=str.substring(str.lastIndexOf("\\")+1);
    if(fileName!=null)return fileName;
    else return null;
    }
    void saveFile(long start,long end,File inFile,File outFile){
    try{
    //System.out.println(outFile.toString());
    FileOutputStream fos=new FileOutputStream(outFile);
    RandomAccessFile fis=new RandomAccessFile(inFile,"r");//随机读
    byte b1;
    fis.seek(start);
    while(start<end)
    {
    b1=fis.readByte();//从临时文件中读1字节
    fos.write(b1);//把字节写入文件
    start++;
    }
    fos.close();
    fis.close();
    }catch(Exception e){System.out.println(e.getMessage());}}
    %><%
    try{
    //windows:
    //String path=request.getRealPath("")+"\\";//取得当前目录在服务器上的实际位置
    //****在UNIX系统中使用下面一句
    String path=request.getRealPath("");
    //建立临时文件
    File tmpFile=new File(path,"formData.tmp");
    saveStreamData2tmpFile(request.getInputStream(),tmpFile);//把流保存到临时文件以便进一步处理
    RandomAccessFile tmpRAF=new RandomAccessFile(tmpFile,"r");//读取临时文件f1,为便于定位和解析,使用RandomAccessFile类
    int i;
    String line=null;
    String boundary="";//记录表单定界符
    line=tmpRAF.readLine();//第一行就是定界符
    boundary=line.substring(0,line.length()-1);//去掉行末回车,unix下减1
    while((line=tmpRAF.readLine())!=null)//第2行开始不停地读取和处理
    {
    if(line.startsWith("Content-Disposition: form-data; name=\"")){//表单域开始
    fieldName=getFieldName(line);
    if(line.indexOf("filename=\"")!=-1){//file域开始
    fileName=getFileName(line);
    fields.put(fieldName,fileName);
    line=tmpRAF.readLine();//跳过content-type行
    line=tmpRAF.readLine();//跳过空行
    start=tmpRAF.getFilePointer();//得到当前位置即文件开始位置
    long end=tmpRAF.length();//默认文件内容的结束位置就是临时文件的尾部
    while((line=tmpRAF.readLine())!=null)//继续读,读到文件末
    {
    if(line.indexOf(boundary)!=-1)//如果未到下一个域定界符
    {
    end=tmpRAF.getFilePointer()-line.length()-2;//去掉行末的2个回车和换行(cr+lf):
    //1个来自于http请求在表单数据结束时加上的行结束标志,一个来自于readline方法返回的字
    //串并不包括行结束符,因此用length方法得到的字节数比实际的字节数少2。如果unix则减2
    break;
    }
    }
    ///现在文件的起始、结束位置都找到了,可以保存了
    if(fileName==null||fileName.equals("")){}else{
    if(fieldName.equals("content")){//title域
    //windows:
    //saveName=path+"upload\\"+fileName;
    //unix:
    saveName=path+"upload/"+fileName;
    }else{//pic1,pic2,att1,att2域
    //windows:
    //saveName=path+"attach\\"+fileName;
    //unix:
    saveName=path+"attach/"+fileName;
    }
    saveFile(start,end,tmpFile,new File(saveName));
    out.println("<font style={font-size:14px;font-style:italic;color:red}><p>");
    out.println("文件"+fileName+"上传至服务器 "+(end-start)+" bytes 成功!");
    }
    //line=tmpRAF.readLine(); }else{//其他表单域
    line=tmpRAF.readLine();//跳过空行,其他域没有content-type行,所以下一行就是表单值
    while((line=tmpRAF.readLine()).indexOf(boundary)!=-1){//如果未到下一个域定界符
    //其实我的表单都是单行文本框,其值不会超过一行,所以这个循环只会循环一次(无聊)
    }
    fields.put(fieldName,line);//加入hash表保存 */
    } }else{

    }
    }
    /*////
    Enumeration enum=fields.keys();
    while(enum.hasMoreElements()){
    String str=(String)enum.nextElement();
    out.println(str+":"+(String)fields.get(str)+"<br>");
    }
    ////*/
    }catch(Exception e){out.println("文件上传错误:"+e);}
    %>
    <%
    String title,content,date,messenger;
    String pic1="";
    String pic1name="";
    String pic2="";
    String pic2name="";
    String att1="";
    String att1name="";
    String att2="";
    String att2name="";
    title=getFieldValue("title");
    content="upload/"+getFieldValue("content");//文件名还要加上保存路径
    if(getFieldValue("pic1").equals("")){}
    else{
    pic1="attach/"+getFieldValue("pic1");
    pic1name=getFieldValue("pic1name");
    }
    if(getFieldValue("pic2").equals("")){}
    else{
    pic2="attach/"+getFieldValue("pic2");
    pic2name=getFieldValue("pic2name");
    }
    if(getFieldValue("att1").equals("")){}
    else{
    att1="attach/"+getFieldValue("att1");
    att1name=getFieldValue("att1name");
    }
    if(getFieldValue("att2").equals("")){}
    else{
    att2="attach/"+getFieldValue("att2");
    att2name=getFieldValue("att2name");
    }
    Date now=new Date();
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    date=sdf.format(now);
    messenger="";
    messenger=(String)session.getAttribute("username");
    int readnum=0;
    title=getCHS(title);
    messenger=getCHS(messenger);
    pic1name=getCHS(pic1name);
    pic2name=getCHS(pic2name);
    att1name=getCHS(att1name);
    att2name=getCHS(att2name);
    /*access数据库:
    String sql="insert into notice(title,content,uploaddate,messenger,readnum,pic1,pic1name,pic2,pic2name," +
    "att1,att1name,att2,att2name) values('"+title+"','"+content+"','"+date+"','"+messenger+
    "',"+readnum+",'"+pic1+"','"+pic1name+"','"+pic2+"','"+pic2name+"','"+
    att1+"','"+att1name+"','"+att2+"','"+att2name+"')";
    */
    //oracle数据库:
    String sql="insert into notify(id,title,content,uploaddate,messenger,readnum,pic1,pic1name,pic2,pic2name," +
    "att1,att1name,att2,att2name) values(noticeId.nextVal,'"+title+"','"+content+"',"+
    "to_date('"+date+"','YYYY-MM-DD HH24:MI:ss'),'"+messenger+
    "',"+readnum+",'"+pic1+"','"+pic1name+"','"+pic2+"','"+pic2name+"','"+
    att1+"','"+att1name+"','"+att2+"','"+att2name+"')";
    stmt.executeUpdate(sql);
    out.println("<p>数据库更新成功!");
    String str="<p align=center><a href='javascript:window.opener=null;window.close()'>关闭</a>&nbsp;&nbsp;&nbsp;&nbsp<a href='title.jsp' target='_self'>返回首页</a>&nbsp;&nbsp;&nbsp;&nbsp<a href='postform.jsp' target='_self'>继续张贴</a></p></font>";
    out.println(str);
    %>
    </body></html>