java实现文件上传到数据库

背景: 刚入职,到了一个官僚主义严重的公司,接到一个腐败的项目,需要把文本扫描为图片上传到数据库,外面文件夹不留扫描文件电子档。拿到任务后,我查了些资料发现一些思路,
我的解决方案:
1、首先将文件上传到服务器,
2、将文件传到数据库
3、上传完成后,删除文件

好了思路就这么样了,开始码代码吧…………
申明一下,代码已打包(灰常详细)
http://download.csdn.net/detail/zengshunyao/8548493

package com.funi.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

import com.funi.dao.MaterialDao4Oracle;
import com.funi.exception.FUNIException;
import com.funi.upload.FUNIFile;

/**
 * Servlet implementation class Upload
 */
@Deprecated
@WebServlet(description = "上传文件服务", urlPatterns = { "/uploadServletDemo" })
public class Upload extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private String filePath; // 文件存放目录
    private String tempPath; // 临时文件目录

    public Upload() {
        super();
    }

    @Override
    public void init(ServletConfig config) throws ServletException {

        super.init(config); // 从配置文件中获得初始化参数 filePath =
        config.getInitParameter("filepath");
        tempPath = config.getInitParameter("temppath");

        ServletContext context = getServletContext();

        filePath = context.getRealPath(filePath);
        tempPath = context.getRealPath(tempPath);

        // 如果路径不存在,则创建路径
        File pathFile = new File(filePath);
        File pathTemp = new File(tempPath);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        if (!pathTemp.exists()) {
            pathTemp.mkdirs();
        }
        System.out.println(filePath);
        System.out.println("文件存放目录、临时文件目录准备完毕 ...");

    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        PrintWriter pw = response.getWriter();

        try {
            DiskFileItemFactory diskFactory = new DiskFileItemFactory();
            // threshold 极限、临界值,即硬盘缓存 1G
            diskFactory.setSizeThreshold(1000 * 1024 * 1024);
            // repository 贮藏室,即临时文件目录
            diskFactory.setRepository(new File(tempPath));

            ServletFileUpload upload = new ServletFileUpload(diskFactory);
            // 设置允许上传的最大文件大小 1G upload.setSizeMax(1000 * 1024 * 1024);
            // 解析HTTP请求消息头
            List<FileItem> fileItems = upload
                    .parseRequest(new ServletRequestContext(request));
            Iterator<FileItem> iter = fileItems.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    System.out.println("处理表单内容 ...");
                    processFormField(item, pw);
                } else {
                    System.out.println("处理上传的文件 ...");
                    processUploadFile(item, pw);
                }
            }// end while()

            pw.close();
        } catch (Exception e) {
            System.out.println("使用 fileupload 包时发生异常 ...");
            e.printStackTrace();
        }

        try {
            new FUNIFile().upload(request, response, null);
        } catch (FUNIException e) {

            e.printStackTrace();
        }
    }

    // 处理表单内容
    private void processFormField(FileItem item, PrintWriter pw)
            throws Exception {
        String name = item.getFieldName();
        String value = item.getString();
        pw.println(name + " : " + value + "\r\n");
    }

    // 处理上传的文件
    private void processUploadFile(FileItem item, PrintWriter pw)
            throws Exception {
        // 此时的文件名包含了完整的路径,得注意加工一下
        String filename = item.getName();
        System.out.println("完整的文件名:" + filename);
        int index = filename.lastIndexOf("\\");
        filename = filename.substring(index + 1, filename.length());

        long fileSize = item.getSize();

        if ("".equals(filename) && fileSize == 0) {
            System.out.println("文件名为空 ...");
            return;
        }

        File uploadFile = new File(filePath + "/" + filename);
        if (!uploadFile.exists()) {
            uploadFile.createNewFile();
        }
        item.write(uploadFile);

        // 写入到数据库
        new MaterialDao4Oracle().add(uploadFile);
        // 完成写入
        uploadFile.delete();//删除文件不留

        pw.println(filename + " 文件保存完毕 ...");
        pw.println("文件大小为 :" + fileSize + "\r\n");
    }

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

插入数据库代码

package com.funi.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;

import oracle.jdbc.OracleResultSet;
import oracle.jdbc.driver.OraclePreparedStatement;

import com.funi.util.DBConn4Oracle;


/**
 * 
 * 
 * 
 * @author zengshunyao
 * @version 1.0
 */
public class MaterialDao4Oracle {

    private Connection conn;

    public MaterialDao4Oracle() {
        super();
        conn = DBConn4Oracle.getConn();
    }

public InputStream find(int id) throws SQLException, IOException {
        String selectSql = "select pic from  IMAGEDETAIL  where  id=?";
        OraclePreparedStatement ps = (OraclePreparedStatement) conn
                .prepareStatement(selectSql);
        ps.setInt(1, id);

        OracleResultSet rs = (OracleResultSet) ps.executeQuery();
        InputStream ins = null;
        if (rs.next()) {
            java.sql.Blob blob = rs.getBlob("pic");
            ins = blob.getBinaryStream();
        }
        return ins;
    }
//
//  public Blob getBlob(int id) throws SQLException, IOException {
//      String selectSql = "select pic from  IMAGEDETAIL  where  id=?";
//      OraclePreparedStatement ps = (OraclePreparedStatement) conn
//              .prepareStatement(selectSql);
//      ps.setInt(1, id);
//
//      OracleResultSet rs = (OracleResultSet) ps.executeQuery();
//      java.sql.Blob blob = null;
//      if (rs.next()) {
//          blob = rs.getBlob("pic");
//      }
//      return blob;
//  }

    public int add(File file) throws IOException, SQLException {
        OraclePreparedStatement ps = null;
        OracleResultSet rs = null;
        FileInputStream fin = null;
        int influencenum = -1;
        // if (conn.getAutoCommit())
        // 此处不建议判断,看到源码后,你就知道了(全是线程安全[synchronized])
        conn.setAutoCommit(false);// 设置事务手动提交

        String inertSql = "insert into IMAGEDETAIL(id,pic) values(?,empty_blob())";
        String selectSql = "select pic from IMAGEDETAIL where id = ? for update";

        ps = (OraclePreparedStatement) conn.prepareStatement(inertSql);
        ps.setInt(1, 3);
        influencenum = ps.executeUpdate();

        ps = (OraclePreparedStatement) conn.prepareStatement(selectSql);
        ps.setInt(1, 3);
        rs = (OracleResultSet) ps.executeQuery();

        if (rs.next()) {
            oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("pic");
            OutputStream out = blob.getBinaryOutputStream();
            byte[] b = new byte[blob.getBufferSize()];
            int len = 0;
            fin = new FileInputStream(file);
            while ((len = fin.read(b)) != -1)
                out.write(b, 0, len);
            fin.close();
            out.flush();
            out.close();
            conn.commit();
            rs.close();
            // conn.close();
        }
        return influencenum;
    }
}

然后是单例模式的获得数据库连接

        package com.funi.util;
     import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.SQLException;

/**
*
* @author zengshunyao
* @version 1.0
*/
public class DBConn4Oracle {

// 驱动程序名
private final String driver = "oracle.jdbc.driver.OracleDriver";

// URL指向要访问的数据库名scutcs
private final String url = "jdbc:oracle:thin:@localhost:1521:orcl";

// MySQL配置时的用户名
private final String user = "funi";

// Java连接MySQL配置时的密码
private static final String password = "yourpassword";

private static Connection conn = null;

private DBConn4Oracle() {
    try {
        // 加载驱动程序
        Class.forName(driver);
        // 连续数据库
        conn = DriverManager.getConnection(url, user, password);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public static final Connection getConn() {
    if (conn == null) {
        synchronized (DBConn4Oracle.class) {
            if (conn == null) {
                new DBConn4Oracle();
            }
        }
    }
    try {
        if (!conn.isClosed())
            System.out.println("Succeeded connecting to the Database!");
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return conn;
}

public static void main(String[] args) {
    System.out.println(DBConn4Oracle.getConn());
}

}

最后就是jsp了

<form name="uploadForm" method="post" enctype="multipart/form-data"
        action="UP">
        Name:<input type="text" name="username" /> <br /> File1:<input
            type="file" name="file1" /> <br /> File2:<input type="file"
            name="file2" /> <br /> <input type="submit" name="submit"
            value="上传"> <input type="reset" name="reset" value="重置">
    </form>

比较值得注意的几个地方

1。db.conn.setAutoCommit(false); 需要将自动提交设置为false。否则会报一个
java.sql.SQLException: ORA-01002: fetch out of sequence的错误。

2。要存入文件需要oracle用blob字段,并且注意Oracle的 BLOB一定要用EMPTY_BLOB()初始化
在insert之后,要select原来的文件应该用for update
比如:select filebody from filetest where filename=? for update
否则会报 ORA-22920: row containing the LOB value is not locked的错误。

其他基本OK

代码打包http://download.csdn.net/detail/zengshunyao/8548493
随便转载,切记留下出处http://blog.csdn.net/zengshunyao/article/details/44757761

  • 9
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值