Loading...

          java .net

          2007年4月12日 星期四

          昨天干啥了?呵呵,昨天沒過來寫,哈哈現在是周五了,噢對,哈哈,昨天有活干了,讓我做一個上傳圖片,把圖片報存在數據庫中,然后再讀出來顯示,要能查 詢、添加、刪除。好了動手吧,以前做過一個上傳圖片,但是不是把圖片報存在數據庫中,大同小異了。把關鍵代碼貼在這里,供以后參考。

          -----------------------------上傳頁面---------------------------------------------------------------
          <%@page contentType="text/html; charset=gb2312" %>
          <%@ taglib uri="/WEB-INF/struts-html" prefix="html"%>

          <html>
              <head>
                  <title>上傳圖片</title>
              </head>


          <body>
              <h2>選擇圖片(JPEG格式, 大小小于1M)</h2>
              <br>
             
              <html:form action="/upload.do" enctype="multipart/form-data">
                  <html:errors/>
                  <table>
                  <tr>
                      <TD><html:file property="file" size="50"></html:file></TD>
                  </tr>
                  <TR height="20" valign="top" topmargin="0">
                      <TD>備注:</TD>   
                  </tr>
                  <tr>
                      <TD><html:textarea rows="3" cols="40" property="memo"></html:textarea></TD>       
                  </TR>
                  <tr>
                      <tr height="20">
                  </tr>
                  <tr>
                      <TD height="22" align="center">
                  <html:submit>&nbsp;上&nbsp;&nbsp;傳&nbsp;</html: submit>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="&nbsp;取&nbsp;&nbsp;消&nbsp;" onclick="window.close()"/></TD>
                  </tr>
                 
                  </table>
              </html:form>
          </body>

          </html>

          --------------------------------------action--UploadAction-----------------------------------------------------

          public ActionForward execute(ActionMapping mapping, ActionForm form,
                      HttpServletRequest request, HttpServletResponse response) throws Exception {
                 
                  response.setCharacterEncoding("gb2312"); //如果不設置,彈出的提示框是亂碼
                 
                  UploadForm uploadForm = (UploadForm) form;
                  FormFile file = uploadForm.getFile();
                  String memo = uploadForm.getMemo();

                  String fileName = file.getFileName();
                  int length = file.getFileSize();

                  InputStream imgStream = null;

                  ActionMessages msgs = new ActionMessages();
                  //向數據庫插入記錄
                  try {
                      imgStream = file.getInputStream();
                      UserImg newUserImg = new UserImg();
                      newUserImg.setImg(imgStream);
                      newUserImg.setImgName(fileName);
                      newUserImg.setMemo(memo);
                      newUserImg.setFileSize(length);
                     
                      if(UploadImageDao.getInstance().insertImg(newUserImg))
                      {
                          response.getWriter().write(
                                  CSScript.alertAndCloseScript(MessageKey.IMAGE_UPLOAD_SUCCESS));
                          return null;
                      }
                      else
                      {
                          msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                                  MessageKey.IMAGE_UPLOAD_FAILED));
                          saveErrors(request, msgs);
                      }
                  } catch (IOException e) {
                     
                      msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                              MessageKey.IMAGE_UPLOAD_FAILED));
                      saveErrors(request, msgs);

                  } finally {
                      try {
                          if (imgStream != null)
                              imgStream.close();
                         
                      } catch (Exception e) {
                          //do nothing here
                      }
                  }
                  return mapping.getInputForward();
                 
                 
              }


          --------------------------------------彈出提示框的類----------------------------------------------------------


          public final class CSScript {
              private static final String S_OPEN = "<script>";
              private static final String S_CLOSE = "</script>";

              public static String alertAndCloseScript(String alert)
              {
                  StringBuffer sb = new StringBuffer(S_OPEN);
                  sb.append("alert('").append(alert).append("!');");
                  sb.append("window.close();");
                  sb.append("window.opener.document.location.reload();");
                  sb.append(S_CLOSE);
                 
                  return sb.toString();
              }
             
              public static String errorScript(String err)
              {
                  StringBuffer sb = new StringBuffer(S_OPEN);
                  sb.append("alert('").append(err).append("!');");
                  sb.append(S_CLOSE);
                 
                  return sb.toString();
              }
             
              public static String alertScript(String alert)
              {
                  StringBuffer sb = new StringBuffer(S_OPEN);
                  sb.append("alert('").append(alert).append("!');");
                  sb.append(S_CLOSE);
                 
                  return sb.toString();
              }
          }


          ---------------------------------------插入數據庫的方法-----------------------------------------------------
          public boolean insertImg(UserImg userImg)
              {
                  Session session = HibernateSessionFactory.getSession();
                  Transaction tran = session.beginTransaction();
                  try
                  {
                      Connection conn = session.connection();
                      PreparedStatement psta = conn.prepareStatement("insert into userImg values(?,?,?)");
                      psta.setString(1,userImg.getImgName());
                      psta.setBinaryStream(2, userImg.getImg(),userImg.getFileSize());
                      psta.setString(3, userImg.getMemo());
                      psta.execute();
                     
                      tran.commit();
                  }
                  catch(Exception e)
                  {
                      e.printStackTrace();
                      tran.rollback();
                      return false;
                  }
                  finally
                  {
                      HibernateSessionFactory.closeSession();
                  }
                  return true;
              }
          注意,這里可以看到涌到了hibernate的session,但還是用的jdbc插入數據庫,是因為hibernate對image類型的字段支持不好。

          -----------------------------------------讀取圖片的action-getImg.do-----------------------------------------------------------

          public ActionForward execute(ActionMapping mapping, ActionForm form,
                      HttpServletRequest request, HttpServletResponse response) {
                  int id = Integer.parseInt(request.getParameter("id"));
                  InputStream inStream = UploadImageDao.getInstance().getImg(id);

                  response.setContentType("image/pjpeg");
                  try {
                      ByteArrayOutputStream baos = new ByteArrayOutputStream();
                      byte[] buffer = new byte[1024];
                      int bytesRead = 0;
                      while ((bytesRead = inStream.read(buffer, 0, 1024)) != -1) {
                          baos.write(buffer, 0, bytesRead);
                      }
                      OutputStream outs = response.getOutputStream();

                      outs.write(baos.toByteArray());

                      outs.flush();

                      inStream.close();
                      baos.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
                  return null;
              }

          頁面中顯示圖片,這么寫
          <img width="100" height="100" src="getImg.do?id=<bean:write name="list" property="id"/>" />

          posted on 2008-08-26 22:06 閱讀(101) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          公告

          希望有一天

          我能用鼠標雙擊我的錢包

          然后選中一張100元

          按住“ctrl+c”

          接著不停的“ctrl+v”

          嘻嘻~~~笑醒~~~



          導航

          <2008年8月>
          272829303112
          3456789
          10111213141516
          17181920212223
          24252627282930
          31123456

          統計

          常用鏈接

          留言簿(6)

          隨筆分類(102)

          隨筆檔案(398)

          文章分類

          文章檔案(10)

          有趣網絡

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 白银市| 鄱阳县| 邵武市| 陇西县| 黔西| 茌平县| 明水县| 高密市| 沁源县| 泸溪县| 琼结县| 循化| 自贡市| 晴隆县| 重庆市| 望谟县| 岳池县| 宜阳县| 清丰县| 无棣县| 张家港市| 安化县| 泗阳县| 鄯善县| 应用必备| 乌兰察布市| 云南省| 祁阳县| 垣曲县| 名山县| 宁安市| 云阳县| 景宁| 宜兴市| 新蔡县| 铜梁县| 叶城县| 河津市| 红桥区| 阿拉善盟| 全南县|