java实现文件上传到数据库
2015-03-30 21:09
337 查看
[code]背景: 刚入职,到了一个官僚主义严重的公司,接到一个腐败的项目,需要把文本扫描为图片上传到数据库,外面文件夹不留扫描文件电子档。拿到任务后,我查了些资料发现一些思路, 我的解决方案: 1、首先将文件上传到服务器, 2、将文件传到数据库 3、上传完成后,删除文件
好了思路就这么样了,开始码代码吧…………
申明一下,代码已打包(灰常详细)
http://download.csdn.net/detail/zengshunyao/8548493
[code]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); } }
插入数据库代码
[code]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; } }
然后是单例模式的获得数据库连接
[code] package com.funi.util; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author zengshunyao
* @version 1.0
*/
public class DBConn4Oracle {
[code]// 驱动程序名 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了
[code]<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
随便转载,切记留下出处/article/1929400.html
相关文章推荐
- java实现excel文件上传并解析内容保存到数据库中
- Java使用servlet实现文件上传至数据库和从数据库下载文件
- Java ckfinder2.6.2实现文件上传破解,获取文件信息添加到数据库中
- JAVA实现邮箱上传文件功能
- 上传文件存入数据库或文件夹路径两种方案的实现
- Java动态显示文件上传进度的简单实现
- [JAVA]彻底抛弃 jspSmartUpload,使用 common-fileupload 实现文件上传
- jQuery教程(十二)使用不苛刻的java script代码实现多文件上传
- java web 利用 commons-fileupload-1.2 实现文件上传 解决 中文乱码& 非文件属性的读取
- Firefox下拖拽客户端文件到浏览器达到上传效果的实现(java例)
- Java实现文件的上传 推荐
- Java动态显示文件上传进度的简单实现
- !JAVA学习提高之---- Struts实现多文件上传
- ASP.NET实现文件的上传与下载(包括用数据库存取文件)
- java实现的ftp文件上传例题
- Flex+java实现文件上传
- JAVA上传文件进度条的实现
- Java动态显示文件上传进度的简单实现 - java2000.net的专栏 - CSDNBlog
- 上传图片文件实现防伪图片水印并写入数据库
- WEB环境中后台自动上传文件至数据库的实现