上传图片并保存到数据库里的servlet代码和jsp代码( 上传图片比实际图片大时,可以用此方法)

common-fileupload是jakarta项目组开发的一个功能很强大的上传文件组件  
import   javax.servlet.*;   
  import   javax.servlet.http.*;   
  import   java.io.*;   
  import   java.util.*;   
  import   java.util.regex.*;   
  import   org.apache.commons.fileupload.*;   
    
    
  public   class   upload   extends   HttpServlet   {   
      private   static   final   String   CONTENT_TYPE   =   "text/html;   charset=GB2312";   
      //Process   the   HTTP   Post   request   
      public   void   doPost(HttpServletRequest   request,   HttpServletResponse   response)   throws   ServletException,   IOException   {   
          response.setContentType(CONTENT_TYPE);   
          PrintWriter   out=response.getWriter();   
          try   {   
          DiskFileUpload   fu   =   new   DiskFileUpload();   
    //   设置允许用户上传文件大小,单位:字节,这里设为2m   
    fu.setSizeMax(2*1024*1024);   
    //   设置最多只允许在内存中存储的数据,单位:字节   
    fu.setSizeThreshold(4096);   
    //   设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录   
    fu.setRepositoryPath("c:\\windows\\temp");   
    //开始读取上传信息   
    List   fileItems   =   fu.parseRequest(request);   
    //   依次处理每个上传的文件   
        Iterator   iter   =   fileItems.iterator();   
    
  //正则匹配,过滤路径取文件名   
        String   regExp=".+\\\\(.+)$";   
    
  //过滤掉的文件类型   
  String[]   errorType={".exe",".com",".cgi",".asp"};   
        Pattern   p   =   Pattern.compile(regExp);   
              while   (iter.hasNext())   {   
                FileItem   item   =   (FileItem)iter.next();   
                //忽略其他不是文件域的所有表单信息   
                if   (!item.isFormField())   {   
                        String   name   =   item.getName();   
                        long   size   =   item.getSize();   
                        if((name==null||name.equals(""))   &&   size==0)   
                                continue;   
                  Matcher   m   =   p.matcher(name);   
                boolean   result   =   m.find();   
                if   (result){   
                        for   (int   temp=0;temp<errorType.length;temp++){   
                        if   (m.group(1).endsWith(errorType[temp])){   
                                    throw   new   IOException(name+":   wrong   type");   
                        }   
                        }   
                        try{   
    
  //保存上传的文件到指定的目录   
    
  //在下文中上传文件至数据库时,将对这里改写   
                            item.write(new   File("d:\\"   +   m.group(1)));   
    
                        out.print(name+"  "+size+"<br>");   
                        }   
                        catch(Exception   e){   
                            out.println(e);   
                        }   
    
                  }   
                else   
                {   
                    throw   new   IOException("fail   to   upload");   
                }   
                }   
        }   
  }   
    catch   (IOException   e){   
        out.println(e);   
    }   
    catch   (FileUploadException   e){   
              out.println(e);   
    }   
      
      }   
  }   
    

下面是个html的上传页面:  
<h1>文件上传演示</h1>   
    
  <form   name="uploadform"   method="POST"   action="/upload"   ENCTYPE="multipart/form-data">   
    
                  <table   border="1"   width="450"   cellpadding="4"   cellspacing="2"   bordercolor="#9BD7FF">   
    
                  <tr><td   width="100%"   colspan="2">   
    
                                                  文件1:<input   name="x"   size="40"   type="file">   
    
                  </td></tr>   
    
                  <tr><td   width="100%"   colspan="2">   
    
                                                  文件2:<input   name="y"   size="40"   type="file">   
    
                  </td></tr>   
    
                  <tr><td   width="100%"   colspan="2">   
    
                                                  文件3:<input   name="z"   size="40"   type="file">   
    
                  </td></tr>   
    
                  </table>   
    
                  <br/><br/>   
    
                  <table>   
    
                  <tr><td   align="center"><input   name="upload"   type="submit"   value="开始上传"/></td></tr>   
    
                </table>   
    
  </form>   

现在介绍上传文件到服务器,下面只写出相关代码:  
   
  以sql2000为例,表结构如下:  
   
  字段名:name  filecode  
   
  类型:   varchar  image  
   
  数据库插入代码为:PreparedStatement   pstmt=conn.prepareStatement("insert   into   test   values(?,?)");  
   
  代码如下: 
  try{   
                            //item.write(new   File("d:\\"   +   m.group(1)));//这段代码如果不去掉,将一同写入到服务器中   
                            int   byteread=0;   
                            InputStream   inStream=item.getInputStream();     //读取输入流,也就是上传的文件内容   
                            pstmt.setString(1,m.group(1));   
                            pstmt.setBinaryStream(2,inStream,(int)size);   
                            pstmt.executeUpdate();   
                            inStream.close();   
                            out.println(name+"  "+size+"<br>");   
                        }   

这样就实现了上传文件至数据库    

==========================================================================
下面代码是在ORACRE中存储任何文件!!  
  字段类型为long   row,看你是否可以用上!!!  
  其中中文路径的问题已经解决!

 package   aaa;   
  //加入相应的包   
  import   javax.servlet.*;   
  import   javax.servlet.http.*;   
  import   java.io.*;   
  import   java.util.*;   
  import   java.sql.*;   
  import   java.sql.PreparedStatement;   
  import   java.sql.Connection;   
  public   class   in   extends   HttpServlet   {   
      private   static   final   String   CONTENT_TYPE   =   "text/html;   charset=GBK";   
      //Initialize   global   variables   
      public   void   init()   throws   ServletException   {   
      }   
      //Process   the   HTTP   Get   request   
      public   void   doPost(HttpServletRequest   request,   HttpServletResponse   response)   throws   ServletException,   IOException   {   
          response.setContentType(CONTENT_TYPE);   
          PrintWriter   out   =   response.getWriter();   
          conn   conn=new   conn();   
        //转换字符串的编码格式   
          request.setCharacterEncoding("GBK");   
    
          //conn.Getconnect().   
        //从上一页面获取相应插入的信息   
            String   XMDM=request.getParameter("XMDM");   
            String   ZLLX=request.getParameter("ZLLX");   
            String   SBRQ=request.getParameter("SBRQ");   
            String   ZLNR=request.getParameter("ZLNR");   
            //将得到的文件路径转换成为相应的文件格式!   
                java.io.File   file=new   java.io.File(ZLNR);   
                //取得文件的长度!!   
              long     l1=file.length();   
              int     s=(int)l1;   
                String   ZLCD=String.valueOf(s);   
                //取得文件名及后缀!!   
                String   ZLHZ=file.getName()   ;   
                //将文件转换成为数据流!!   
                FileInputStream   str=new   FileInputStream(ZLNR);   
                //   String   sql="insert   into   AAA(A,B)   values(?,?)";   
                String   sql="insert   into   GZ_XGZL(XMDM,ZLLX,ZLMC,SBRQ,ZLNR,ZLCD)   values(?,?,?,?,?,?)";   
                //向数据库读流!!连接数据库插入数据。   
              try   {   
                  PreparedStatement   pstmt   =   conn.Getconnect().prepareStatement(sql);   
                  pstmt.setString(1,XMDM);   
                  pstmt.setString(2,ZLLX);   
                  pstmt.setString(3,ZLHZ);   
                  pstmt.setString(4,SBRQ);   
                  pstmt.setBinaryStream(5,str,s);   
                  pstmt.setString(6,ZLCD);   
                  pstmt.execute();   
                    }   
              catch   (SQLException   ex)   {   
              }   
          response.sendRedirect("update.jsp");   
  }}   


===========================================

下面这个适用初学者  

<%@   page   contentType="text/html;   charset=gb2312"%>   
  <%@   include   file="/DataIni/DataOpen.jsp"%>   
  <%@   include   file="/ScriptLib/Init.jsp"%>   
  <%   
  int   iTotalByte,iTotalRead,iReadByte;   
  iTotalByte=request.getContentLength();   
  iTotalRead=0;   
  iReadByte=0;   
  byte[]   Buffer=new   byte[iTotalByte];   
  if(iTotalByte>0)   
  {   
  for(;iTotalRead<iTotalByte;iTotalRead+=iReadByte)   
  {   
  try   
  {   
  iReadByte=request.getInputStream().read(Buffer,iTotalRead,iTotalByte-iTotalRead);   
  }   
  catch(Exception   e)   
  {   
  e.printStackTrace();   
  }   
  }   
  String   strContentType=request.getContentType();   
  //数据处理开始   
  String   strBuffer=new   String(Buffer);   
  %><!--<br>表单数据:<br>strBuffer<br>--><%   
  String   strBoundary="--"+strContentType.substring(strContentType.lastIndexOf("=")+1,strContentType.length());   
  String   strArray[]=strBuffer.split(strBoundary);   
    
  String   strSubString;   
  int   iBegin,iEnd;   
  iBegin=0;iEnd=0;   
  String   strFieldName="";   
  String   strFieldValue="";   
  String   strFilePath="";   
  String   strFileName="";   
  String   strFileType="";   
  boolean   bTrue;   
  bTrue=false;   
  int   iLocation=0;   
  for(int   iIndex=1;iIndex<strArray.length-1;iIndex++)   
  {   
  strSubString=strArray[iIndex];   
  iBegin=strSubString.indexOf("name=\"",0);   
  if(iBegin!=-1)   
  {   
  strFieldName="";strFieldValue="";   
  strFilePath="";strFileName="";strFileType="";   
  iEnd=strSubString.indexOf("\"",iBegin+6);   
  strFieldName=strSubString.substring(iBegin+6,iEnd);   
  iBegin=strSubString.indexOf("filename=\"",0); if(iBegin!=-1)   
  {   
  bTrue=true;   
  }   
  iEnd=strSubString.indexOf("\r\n\r\n",0);   
  if(bTrue==true)   
  {   
  //文件路径   
  strFilePath=strSubString.substring(iBegin+10,strSubString.indexOf("\"",iBegin+10));strFileName=strFilePath.substring(strFilePath.lastIndexOf("\\")+1);   
  strFileType=strSubString.substring(strSubString.indexOf("Content-Type:   ")+14,strSubString.indexOf("\r\n\r\n"));   
  %><!--<br>文件类型:<br>strFileType<br>--><%   
  //文件数据   
  iBegin=strSubString.indexOf("\r\n\r\n",iBegin);   
  strFieldValue=strSubString.substring(iBegin+4);   
  strFieldValue=strFieldValue.substring(0,strFieldValue.lastIndexOf("\n")-1);   
  %><!--<br>文件路径:<br>strFilePath<br>文件名称:<br>strFileName<br>--><%   
  byte[]   pFile=strFieldValue.getBytes();   
  byte[]   pFileExtend=new   byte[pFile.length];   
  iLocation=strBuffer.indexOf("filename=\"",iLocation);   
  for(int   kIndex=iLocation;kIndex<iTotalByte-2;kIndex++)   
  {   
  if(Buffer[kIndex]==13&&Buffer[kIndex+2]==13)   
  {iLocation=kIndex+4;break;}   
  }   
  for(int   nIndex=0;nIndex<pFile.length;nIndex++)   
  {   
  pFileExtend[nIndex]=Buffer[iLocation+nIndex];   
  }   
  /*   
  //保存到Local   Disk;   
  FileOutputStream   pFileOutputStream=new   FileOutputStream("F:\\Site_ColligateStatistic\\UploadFile\\"+strFileName);   
  pFileOutputStream.write(pFileExtend);   
  pFileOutputStream.close();   
  */   
  session.putValue(strFieldName+"_FileType",strFileType);   
  session.putValue(strFieldName+"_FilePath",strFilePath);   
  session.putValue(strFieldName+"_FileName",strFileName);   
  session.putValue(strFieldName,pFileExtend);   
  }   
  else   
  {   
  strFieldValue=strSubString.substring(iEnd+4);   
  strFieldValue=strFieldValue.substring(0,strFieldValue.lastIndexOf("\n")-1);   
  session.putValue(strFieldName,strFieldValue);   
  }   
  bTrue=false;   
  }   
  %><!--<br>表单域名:<br>strFieldName<br>表单域值:<br>strFieldValue<br>--><%   
  }   
  //数据处理结束   
  String   TypeValue,Id,ItemID;   
  TypeValue=(String)session.getValue("TypeValue");   
  ItemID=(String)session.getValue("ItemId");   
  %><br><%=TypeValue%><br><%=ItemID%><br><%   
  if(TypeValue!=null)   
  {   
  int   iDoAction;   
  iDoAction=0;   
  if(TypeValue.indexOf("Add",0)!=-1)   
  {iDoAction=1;}   
  if(TypeValue.indexOf("Modify")!=-1)   
  {iDoAction=2;}   
  if(TypeValue.indexOf("Del")!=-1)   
  {iDoAction=3;}   
  odbcQuery="";   
  Id=(String)session.getValue("RecordId");   
  switch(iDoAction)   
  {   
  case   1:   
  odbcStmt.executeUpdate("insert   into   GeneralSystem(ItemID,Category,Subject,Body,History,Type)   values('"+ItemID+"','"+(String)session.getValue("Category")+"','"+(String)session.getValue("Subject")+"','"+(String)session.getValue("Body")+"',Now(),'"+(String)session.getValue("OLEFile_FileType")+"')");   
  odbcRs=odbcStmtUpdate.executeQuery("select   top   1   *   from   GeneralSystem   order   by   ID   desc");   
  if(odbcRs.next())   
  {   
  byte[]   OLEFile=(byte[])session.getValue("OLEFile");   
  odbcRs.updateBinaryStream("OLEFile",new   ByteArrayInputStream(OLEFile),OLEFile.length);   
  odbcRs.updateRow();   
  odbcRs.close();   
  response.sendRedirect("/System/GeneralSystem/List.jsp");   
  }   
  break;   
  case   2:   
  response.sendRedirect("/System/GeneralSystem/List.jsp");   
  break;   
  case   3:   
  odbcStmt.executeUpdate("delete   from   GeneralSystem   where   ID="+Id);   
  response.sendRedirect("/System/GeneralSystem/List.jsp");   
  break;   
  }   
  }   
  }   
  %>   
  <html>   
    
  <head>   
  <meta   http-equiv="Content-Type"   content="text/html;   charset=gb2312">   
  <meta   name="GENERATOR"   content="Microsoft   FrontPage   4.0">   
  <meta   name="ProgId"   content="FrontPage.Editor.Document">   
  <title></title>   
  <link   rel="stylesheet"   type="text/css"   href="/StyleLib/Default_Style_Sheet.css">   
  </head>   
    
  <body   οnlοad="window.alert('动作失败,系统取消操作!');window.location.href='/System/GeneralSystem/List.jsp';">   
  <%@   include   file="/TemplateLib/Head.jsp"%>   
  <%@   include   file="/TemplateLib/Tail.jsp"%>   
  <%@   include   file="/DataIni/DataClose.jsp"%>   
  </body>   
    
  </html>


=====================================================================
JSP文件上传代码

UploadFileExample1.jsp

view plaincopy to clipboardprint?

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>  
<html>  
<head>  
<title>文件上传</title>  
</head>  
  
<body>  
<form name="form1" method="post" action="AcceptUploadFile.jsp" enctype="multipart/form-data">  
upload file:   
<label>  
<input type="file" name="upfile" size="50" />  
</label>  
<p>  
<label>  
<input type="submit" name="Submit" value="提交" />  
</label>  
</p>  
</form>  
<script type='text/javascript'>  
//<![CDATA[  
document.getElementById('processtime').innerHTML="<span style='font-size: 8pt; font-family: Georgia;'>Run in 158 ms, 10 Queries, Gzip enabled.</span>";  
//]]>  
</script></body>  
</html>  
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<title>文件上传</title>
</head>

<body>
<form name="form1" method="post" action="AcceptUploadFile.jsp" enctype="multipart/form-data">
upload file:
<label>
<input type="file" name="upfile" size="50" />
</label>
<p>
<label>
<input type="submit" name="Submit" value="提交" />
</label>
</p>
</form>
<script type='text/javascript'>
//<![CDATA[
document.getElementById('processtime').innerHTML="<span style='font-size: 8pt; font-family: Georgia;'>Run in 158 ms, 10 Queries, Gzip enabled.</span>";
//]]>
</script></body>
</html>

AccepteUploadFile.jsp

view plaincopy to clipboardprint?
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>   
<%@ page import="java.io.*"%>   
<%!   
public String codeToString(String str)   
{   
String s=str;   
 try  
 {   
 byte tempB[]=s.getBytes("ISO-8859-1");   
 s=new String(tempB);   
 return s;   
 }   
 catch(Exception e)   
 {   
 return s;   
 }   
}   
%>   
<%   
String tempFileName=new String("tempFileName1");//接收上传的文件内容的临时文件的文件名   
File tempFile1=new File("D:/",tempFileName);   
FileOutputStream outputFile1=new FileOutputStream(tempFile1);   
InputStream fileSource1=request.getInputStream();//得到客户端提交的所有数据   
byte b[]=new byte[1000];   
int n;   
while((n=fileSource1.read(b))!=-1)   
{   
outputFile1.write(b,0,n); //将得到的客户端数据写入临时文件   
}   
outputFile1.close();   
fileSource1.close();   
  
RandomAccessFile randomFile1=new RandomAccessFile(tempFile1,"r");   
  
randomFile1.readLine();//读取第一行数据   
String FilePath=randomFile1.readLine();//读取第二行数据,这行数据包括了文件的路径和文件名   
int position=FilePath.lastIndexOf('\\'); //等到文件名   
String filename=codeToString(FilePath.substring(position+1,FilePath.length()-1));   
  
randomFile1.seek(0);//重新定位指针到文件头   
long forthEnterPosition=0;   
int forth=1; //得到第4行回车符号的位置,这是上传文件的开始位置   
while((n=randomFile1.readByte())!=-1&&(forth<=4))   
if(n=='\n')   
{   
 forthEnterPosition=randomFile1.getFilePointer();   
 forth++;   
}   
  
File FileUploadDir=new File("C:/Tomcat5/webapps/ROOT/file/","upload");   
FileUploadDir.mkdir(); //生成上传文件的目录   
File saveFile1=new File("C:/Tomcat5/webapps/ROOT/file/upload/",filename);   
RandomAccessFile randomFile2=new RandomAccessFile(saveFile1,"rw");   
randomFile1.seek(randomFile1.length());   
long endPosition=randomFile1.getFilePointer();//找到上传的文件数据的结束位置,即倒数第4行   
int j=1;   
while((endPosition>=0)&&(j<=4))   
{   
endPosition--;   
 randomFile1.seek(endPosition);   
 if(randomFile1.readByte()=='\n')   
 j++;   
}   
randomFile1.seek(forthEnterPosition);   
long startPoint=randomFile1.getFilePointer();   
while(startPoint<endPosition-1)   
{   
randomFile2.write(randomFile1.readByte());   
 startPoint=randomFile1.getFilePointer();   
}   
randomFile2.close();   
randomFile1.close();   
tempFile1.delete();   
out.print("file:"+filename+" succeed upload!<br/>");   
%>  
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<%@ page import="java.io.*"%>
<%!
public String codeToString(String str)
{
String s=str;
 try
 {
 byte tempB[]=s.getBytes("ISO-8859-1");
 s=new String(tempB);
 return s;
 }
 catch(Exception e)
 {
 return s;
 }
}
%>
<%
String tempFileName=new String("tempFileName1");//接收上传的文件内容的临时文件的文件名
File tempFile1=new File("D:/",tempFileName);
FileOutputStream outputFile1=new FileOutputStream(tempFile1);
InputStream fileSource1=request.getInputStream();//得到客户端提交的所有数据
byte b[]=new byte[1000];
int n;
while((n=fileSource1.read(b))!=-1)
{
outputFile1.write(b,0,n); //将得到的客户端数据写入临时文件
}
outputFile1.close();
fileSource1.close();

RandomAccessFile randomFile1=new RandomAccessFile(tempFile1,"r");

randomFile1.readLine();//读取第一行数据
String FilePath=randomFile1.readLine();//读取第二行数据,这行数据包括了文件的路径和文件名
int position=FilePath.lastIndexOf('\\'); //等到文件名
String filename=codeToString(FilePath.substring(position+1,FilePath.length()-1));

randomFile1.seek(0);//重新定位指针到文件头
long forthEnterPosition=0;
int forth=1; //得到第4行回车符号的位置,这是上传文件的开始位置
while((n=randomFile1.readByte())!=-1&&(forth<=4))
if(n=='\n')
{
 forthEnterPosition=randomFile1.getFilePointer();
 forth++;
}

File FileUploadDir=new File("C:/Tomcat5/webapps/ROOT/file/","upload");
FileUploadDir.mkdir(); //生成上传文件的目录
File saveFile1=new File("C:/Tomcat5/webapps/ROOT/file/upload/",filename);
RandomAccessFile randomFile2=new RandomAccessFile(saveFile1,"rw");
randomFile1.seek(randomFile1.length());
long endPosition=randomFile1.getFilePointer();//找到上传的文件数据的结束位置,即倒数第4行
int j=1;
while((endPosition>=0)&&(j<=4))
{
endPosition--;
 randomFile1.seek(endPosition);
 if(randomFile1.readByte()=='\n')
 j++;
}
randomFile1.seek(forthEnterPosition);
long startPoint=randomFile1.getFilePointer();
while(startPoint<endPosition-1)
{
randomFile2.write(randomFile1.readByte());
 startPoint=randomFile1.getFilePointer();
}
randomFile2.close();
randomFile1.close();
tempFile1.delete();
out.print("file:"+filename+" succeed upload!<br/>");
%>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现JSP页面上传图片保存数据库中的步骤如下: 1. 创建一个带有文件上传表单的JSP页面,例如: ```html <form action="upload.jsp" method="post" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" value="上传"> </form> ``` 2. 在上传的JSP页面中,使用Apache Commons FileUpload或Servlet 3.0以上版本提供的API来处理文件上传操作。例如,使用Apache Commons FileUpload可以通过以下方式将上传的文件保存在服务器上: ```java List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); InputStream fileContent = item.getInputStream(); // 处理文件上传操作 } } ``` 3. 在处理文件上传操作时,将文件内容转换为字节数组,并将字节数组保存数据库中。例如: ```java byte[] imageData = IOUtils.toByteArray(fileContent); // 将字节数组保存数据库中 ``` 4. 在保存数据库之前,需要先连接数据库并打开连接。例如: ```java Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); ``` 5. 将字节数组保存数据库中。这使用PreparedStatement进行参数化查询,将字节数组作为Blob类型的参数插入到数据库中。例如: ```java PreparedStatement statement = connection.prepareStatement("INSERT INTO images (name, data) VALUES (?, ?)"); statement.setString(1, fileName); statement.setBlob(2, new ByteArrayInputStream(imageData)); statement.executeUpdate(); ``` 6. 处理完文件上传和保存数据库后,需要关闭连接。例如: ```java statement.close(); connection.close(); ``` 以上就是JSP页面上传图片保存数据库中的实现步骤。需要注意的是,上传的图片需要进行大小、格式等验证,避免恶意文件上传。同时,需要在web.xml文件中配置multipart-config元素,指定最大文件大小和请求大小限制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值