上传多个文件到Oracle数据库

/*
 * Created on 2005-9-27
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.system.web;

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.jspsmart.upload.*;
import com.mdcl.sc.common.dao.DAOUtils;//dao
import com.sun.image.codec.jpeg.*;
import java.awt.image.*;
import java.awt.*;
import java.net.*;
import java.applet.*;
/**
 * @author hanxr
 *
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class DoUpload extends HttpServlet
{
  private ServletConfig config;

final public void init(ServletConfig config) throws ServletException
  {
    this.config = config;
  }

final public ServletConfig getServletConfig()
  {
    return config;
  }

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

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
        response.setContentType("text/html;charset=gb2312");
        PrintWriter out = response.getWriter();
        String titleid=new String();//标题id
        String fileName=new String();//上传的文件名称
        try
        {
         System.out.println("开始上传附件");
         SmartUpload mySmartUpload = new SmartUpload();
         Connection conn = DAOUtils.getConnection();//链接Oracle数据库
         conn.setAutoCommit(false);//设置不自动提交。
         Statement stmt=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY ,ResultSet.CONCUR_UPDATABLE);
         ResultSet rs=null;
         mySmartUpload.initialize(config, request, response);
         mySmartUpload.setMaxFileSize(1024 * 1024 * 10);//上传文件最大尺寸
         mySmartUpload.upload();//上传
         Enumeration enumer=mySmartUpload.getRequest().getParameterNames();
         String strsql=new String();//sql语句
         for (int i=0;i<mySmartUpload.getFiles().getCount();i++)//循环上传附件
         {
            com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i);//取得文件
            fileName=myFile.getFileName();//取得文件名
            //String
   // filetype=mySmartUpload.getFiles().getFile(i).getFileExt();//获取后缀名
            if(!myFile.isMissing())
            {
                myFile.saveAs("uploadfile/"+fileName);//保存上传的文件到服务器的uploadfile目录下
                System.out.println("文件名:"+fileName);//后台显示文件名
                java.io.File sfile=new java.io.File(request.getRealPath("")+"\\uploadfile\\"+fileName);//创建文件对象
                java.io.InputStream inStream=new java.io.FileInputStream(sfile);//将文件读到流中
                int fileSize=myFile.getSize();//获取文件大小(字节)
                if(fileSize>mySmartUpload.getSize())
                {
                    System.out.println("上传文件过大!");
                    int err=1/0;
                  }
                  System.out.println("文件大小:"+(int)(fileSize/1024)+"KB");//后台显示文件大小
                  if(fileSize!=0)
                  {
                      String contenttype = myFile.getContentType();//获得文件类型
                      System.out.println("文件类型:"+contenttype);//后台显示文件类型
                      String blobzd=new String();//blob字段名
                        if(!contenttype.trim().equals("image/pjpeg") && !contenttype.trim().equals("image/gif"))
                        {
                          System.out.println("上传的文件不是规定格式的图片!");
                          int err=1/0;
                        }
                        blobzd="img";//图片表图片字段名称
                        strsql="insert into tblpicture(id,titleid,num,picture,img,thumbnail) values(pictureid.nextval,"+titleid+","+fileSize+",'"+contenttype.trim()+"',empty_blob(),empty_blob())";//插入一条空图片数据进图片表
                        stmt.execute(strsql);
                        //------------生成缩略图------------------//
                        BufferedImage image;
                        Image img=null;
                        Toolkit tk=Toolkit.getDefaultToolkit();
                        Applet app=new Applet();
                        MediaTracker mt = new MediaTracker(app);
                        img=tk.getImage(request.getRealPath("")+"\\uploadfile\\"+fileName);//获取原始图
                        mt.addImage(img, 0);
                        mt.waitForID(0);
                        double rate1=((double)img.getWidth(null))/120.0+0.1;
                        double rate2=((double)img.getHeight(null))/120.0+0.1;
                        double rate=rate1>rate2?rate1:rate2;
                        int new_w=(int)(((double)img.getWidth(null))/rate);
                        int new_h=(int)(((double)img.getHeight(null))/rate);
                        BufferedImage buffImg = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
                        Graphics g = buffImg.createGraphics();
                        g.setColor(Color.white);
                        g.fillRect(0,0,new_w,new_h);
                        g.drawImage(img,0,0,new_w,new_h,null);//绘制缩略图
                        g.dispose();
                        java.io.OutputStream tempout=null;
                        java.io.File tempfile=new java.io.File(request.getRealPath("")+"\\uploadfile\\"+fileName+"_small.jpg");
                        tempout= new FileOutputStream(tempfile);
                        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(tempout);
                        encoder.encode(buffImg);
                        if(tempout!=null)tempout.close();
                        //------------缩略图生成完毕----------------//
                        //------------缩略图入库-------------------//
                        java.io.InputStream tempinstream=new java.io.FileInputStream(tempfile);//将缩略图文件读到流中
                        strsql="select thumbnail from tblpicture where titleid="+titleid+" and dbms_lob.getlength(thumbnail)=0 for update ";//选择图片表的缩略图字段更新
                        rs=stmt.executeQuery(strsql);
                        if (rs !=null && rs.next())//写缩略图数据进blob类型字段
                        {
                          System.out.println("缩略图入库!");
                          oracle.sql.BLOB tempblob=((oracle.jdbc.OracleResultSet)rs).getBLOB("thumbnail");
                          tempout = tempblob.getBinaryOutputStream();
                          byte[] tempbytes = new byte[(int) tempfile.length()];//创建缓冲区
                        tempinstream.read(tempbytes);
                         tempout.write(tempbytes);
                         tempout.flush();
                        stmt.execute("commit");
                          if(tempout!=null)tempout.close();
                        }
                        if(tempinstream!=null)tempinstream.close();
                        if(tempfile!=null){if(tempfile.delete())System.out.println("缩略图入库完毕!临时文件已删除!");}//删除缩略图临时文件
                        //---------------缩略图入库完毕-------------//
                        strsql="select img from tblpicture where titleid="+titleid+" and dbms_lob.getlength(img)=0 for update ";//选择图片表的图片字段更新
                        rs=stmt.executeQuery(strsql);
                      if (rs !=null && rs.next())//写数据进blob类型字段
                      {
                        oracle.sql.BLOB blob=((oracle.jdbc.OracleResultSet)rs).getBLOB(blobzd);
                        java.io.OutputStream outStream = blob.getBinaryOutputStream();
                        byte[] bytes = new byte[fileSize];//创建缓冲区
                      inStream.read(bytes);
                       outStream.write(bytes);
                       outStream.flush();
                      stmt.execute("commit");
                        if(outStream!=null)outStream.close();
                      }
                  }
                  if(inStream!=null)inStream.close();
                  if(sfile!=null){if(sfile.delete())System.out.println("临时文件已删除");}//删除临时文件
              }
           }
           if(rs!=null)rs.close();
           if(stmt!=null)stmt.close();
           if(conn!=null)conn.close();
           System.out.println("文件上传完毕");
          }
          catch(Exception ex1)
          {
            System.out.println(ex1.toString());
          }

}
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwpjjg.html