文件上传入数据库

来源:互联网 发布:网络销售许可证烟草 编辑:程序博客网 时间:2024/05/16 06:37

比如向表notice_file表中添加文件,将文件以blob格式的字段进行存储。

action中直接增加属性:

private File[] file; // 这里对应的jsp页面上的两个字段.没啥可以说.
 private String[] fileFileName; // 注意,这个表示的是file这个上传对象的文件名..这个是struts2自己封装的.可以自动获取,不用和上一节一样需要我们自己去写代码..
         // 这里的名字后面部分"FileName"是固定的,前面的file就是上面那个file.也就是说和jsp页面的那个字段的name是对应的..
 private String[] fileContentType; // 这里也同样,表示文件类型.struts2已经封装好的.后面的"ContentType"也是固定的.

或者写在action的model类中。

在前台jsp页面使用struts标签或者其他方式创建file标签,name为file //这个name值必须与后台中的属性保持一致。

action中部分代码如下:

if (model.getFile() != null && model.getFile().length > 0) {
     for (int i = 0; i < model.getFile().length; i++) {
      int index = model.getFileFileName()[i].lastIndexOf(".");
      String name = model.getFileFileName()[i].substring(0,
        index);
      String ext = model.getFileFileName()[i]
        .substring(index + 1);
      NoticeFile file = new NoticeFile();
      file.setNoticeId(notice.getNoticeId());
      file.setFileExt(ext);
      file.setFileName(name);
      file.setFileType(model.getFileContentType()[i]);
      file.setFileSize(model.getFile()[i].length());
      noticeFileService.insertSelective(file); //先插入表中除blob字段以外的其他字段
      noticeFileService.updateFileData(file.getFileId(),
        new FileInputStream(model.getFile()[i]));//再将blob字段进行入库
     }
    }

 

public int updateContent(final long noticeId, final InputStream contentIs) {
  String sql = "update notice \n" + "set notice_content = empty_blob() "
    + "where notice_id = " + noticeId;

  String sql2 = "select notice_content   from notice   where notice_id = "
    + noticeId + " for update";

  Connection conn = null;
  Statement pstmt = null;
  ResultSet rs = null;
  try {
   conn = AppContext.getDs().getConnection();
   conn.setAutoCommit(false);
   pstmt = conn.createStatement();

   pstmt.executeUpdate(sql);
   conn.commit();

   rs = pstmt.executeQuery(sql2);
   if (rs.next()) {
    Blob blob = rs.getBlob("notice_content");
    OutputStream out = ((oracle.sql.BLOB) blob)
      .getBinaryOutputStream();
    byte[] b = new byte[((oracle.sql.BLOB) blob).getBufferSize()];
    int len = 0;
    while ((len = contentIs.read(b)) != -1)
     out.write(b, 0, len);
    contentIs.close();
    out.flush();
    out.close();
   }
   conn.commit();
   return 1;
  } catch (Exception e) {
   e.printStackTrace();
   return 0;
  } finally {
   try {
    conn.setAutoCommit(true);
   } catch (Exception e) {
    e.printStackTrace();
   }
   BeanUtil.closeResource(rs, pstmt, conn);
  }
 }

 

 

0 0