关于图片上传到服务器并保存到数据库,然后读出显示到页面上的一系列例子.cn/s/blog_4b8712eb010007zx.html(2007-02-03 09:08:23)转载▼分类:JAVA一、addImg.jsp 类似网易邮箱的多附件上传,无刷新动态添加<%@ page language="java" contentType="text/html; charset=gbk"pageEncoding="gbk"import=",,,java.util.*"%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01Transitional//EN"><html><head><%String path = request.getContextPath();BookDAO bdao = new BookDAO();Book b = new Book();List booklist = bdao.findAll();if (booklist == null || booklist.size() == 0) { booklist = new ArrayList();}%><script>function addUploadFile(){var _table =document.getElementByIdx("uploadTable"); var rowIndex =_table.getElementsByTagName_r("tr").length -1;var _tr = _table.insertRow(rowIndex);var _td1 = _tr.insertCell(0);var _td2 = _tr.insertCell(1);var _td3 = _tr.insertCell(2);_tr.bgColor = '#E1E8F4';_tr.setAttribute("height","27");_tr.setAttribute("id",rowIndex.toString());_td1.setAttribute("width","15%");_td1.setAttribute("align","center");_td2.setAttribute("align","left");_td2.setAttribute("colspan","2");_td3.setAttribute("width","5%");var td1 = '图片';var td2 = '<input type="FILE"name="file'+rowIndex.toString()+'" size="20 " style="width:100%; font-size:12px; border:1px solid #555555;">';var td3 = '<input type="button"class="button"name="btnDel"'+rowIndex.toString()+' value="删除"onclick="delUploadFile('+rowIndex.toString( )+');">';_td1.appendChild(document.createTextNode(td1));_td2.appendChild(document.createElement(t d2));_td3.appendChild(document.createElement(t d3));}function delUploadFile(fileIndex){if (confirm('确定要删除么?')){var _table =document.getElementByIdx("uploadTable"); _table.deleteRow(document.getElementById x(fileIndex.toString()).rowIndex);}}function submitPage(){var form=document.getElementByIdx("form1");var flag=0;for(i=0;i<"input").length;i++){if("input")[i].type=="file"){if("input")[i].value==""){alert("请不要有空的上传文件框") flag=1;}}}if(flag==0){form.submit();}}</script></head><body><form name="form1" method="post" action="/TianaiSearch/UploadImage" ENCTYPE="multipart/form-data"><table width="100%" border="0" cellspacing="1" cellpadding="0"bgcolor="#869DD2"><tr><td><table id="uploadTable" width="100%" border="0" cellpadding="4" cellspacing="1" align="center" bgcolor="#ffffff"><tr><td height="40" colspan="2"><spanclass="style1 tt style1"><strong>上传文件信息</strong></span></td></tr><tr height="24" bgcolor="#EAEEF7"><td width="15%" align="center">对应文档</td><td align="left" colspan="2"><input type="text" name="file_id"size="20" style="width:100%; font-size:12px; border:1px solid #555555;"></tr><tr height="24" bgcolor="#EAEEF7"><td width="15%" align="center">来自书目</td><td align="left" colspan="2"><select name="book_id"><%for(int i=0;i<booklist.size();i++){b=(Book)booklist.get(i);%><optionvalue="<%=b.getId() %>"><%=b.getName() %></option><%}%></select></tr><tr height="24" bgcolor="#EAEEF7"><td width="15%" align="center">开始页码</td><td align="left" colspan="2"><input type="text"name="start_page_no" size="20"style="width:100%; font-size:12px; border:1px solid #555555;"></td></tr><tr height="27" bgcolor="#E1E8F4"><td width="15%" align="center">图片</td><td align="left" colspan="2"><input type="FILE"name="upload" size="20" style="width:100%;font-size:12px; border:1px solid #555555;"> </td></tr><tr bgcolor="#EAEEF7"><td colspan="4" align="center"><input type="button" class="button" name="addUpload" value="添加文件" onclick="addUploadFile();"> <input type="button" class="button" name="smtbtn" value="确认上传"onclick="submitPage();"> <input type="reset" class="button" name="bt4" value="重置"></td></tr></table></td></tr></table></form></body></html>二、UploadImage.servlet doPost方法//实例化上载beanmySmartUpload = new ;//初始化mySmartUpload.initialize(this.getServletCo nfig(),request,response);request.setCharacterEncoding("gbk");//设置上载的最大值mySmartUpload.setMaxFileSize(500 * 1024 * 1024);//上载文件try {mySmartUpload.upload();} catch (SmartUploadException e) {// TODO 自动生成catch 块e.printStackTrace();}//循环取得所有上载的文件for (int i = 0; i <mySmartUpload.getFiles().getCount(); i++) { //取得上载的文件myFile = mySmartUpload.getFiles().getFile(i);if (!myFile.isMissing()) {//取得上载的文件的文件名String myFileName =myFile.getFileName();//取得不带后缀的文件名String suffix = myFileName.substring(0, myFileName.lastIndexOf('.'));//取得后缀名String ext =mySmartUpload.getFiles().getFile(0).getFileExt();//取得文件的大小int fileSize = myFile.getSize();//保存路径String aa =getServletContext().getRealPath("/") + "jsp\\"; ;String trace = aa + myFileName;//取得别的参数// String explain = (String) mySmartUpload.getRequest()// .getParameter("text");// String send = (String) mySmartUpload.getRequest()// .getParameter("send");String sBook_id =(String)mySmartUpload.getRequest().getPara meter("book_id");"book id is "+sBook_id);int iBook_id = 0;if (sBook_id != null &&sBook_id.trim().length() != 0) {iBook_id = Integer.parseInt(sBook_id); }String sFile_id =(String)mySmartUpload.getRequest().getPara meter("file_id");"file_id is "+sFile_id);int iFile_id = 0;if (sFile_id != null &&sFile_id.trim().length() != 0) {iFile_id = Integer.parseInt(sFile_id);}String sStartPage_no =(String)mySmartUpload.getRequest().getPara meter("start_page_no");int iStartPage_no = 0;if (sStartPage_no != null && sStartPage_no.trim().length() != 0) {iStartPage_no =Integer.parseInt(sStartPage_no);}int iPage_no=0;if(iStartPage_no!=0){iPage_no=iStartPage_no+i;}//将文件保存在服务器端try {myFile.saveAs(trace, mySmartUpload.SAVE_PHYSICAL);} catch (SmartUploadException e) {e.printStackTrace();}//下面的是将上载的文件保存到数据库中//将文件读到流中file = new ;fis = newfile);;//打开数据库Image image = new Image(0, iFile_id, fis, iBook_id,iPage_no);ImageDAO idao = new ImageDAO();idao.add(image);}}}到此,图片就已经存进数据库了,接着看怎么把他显示到页面上三、showImage() servlet中使用private void ShowImage(String id, HttpServletRequest request,HttpServletResponse response) throws IOException {Connection conn = null;final String CONTENT_TYPE = "image/*"; ResultSet rs = null;Statement stmt = null;String SQLString = ""; // 定义查询语句String M_EorrMenage = ""; // 定义错误信息变量InputStream in = null; // 定义输入流int len = 10 * 1024 * 1024; // 定义字符数组长度// Initialize global variablesresponse.setContentType(CONTENT_TYP E);// PrintWriter out = response.getWriter(); try {SQLString = "select * from image where id=" + id;} catch (Exception e) {e.printStackTrace();response.setContentType("text/html; charset=gbk");M_EorrMenage = "请输入图片ID号"; M_EorrMenage = newString(M_EorrMenage.getBytes("ISO8859_1"), "GBK");// out.println("<%@ pagecontentType='text/html; charset=gbk' %>"); // out.println("<html>");//out.println("<head><title>id</title></head>"); // out.println("<body>");// out.println("<p>" + M_EorrMenage + "</p>");// out.println("</body></html>");}try {conn =DBConnection.newInstacne().getConnection( );stmt = conn.createStatement();rs = stmt.executeQuery(SQLString);} catch (SQLException ex) {"aq.executeUpdate:" + ex.getMessage());M_EorrMenage = "对不起,数据库无法完成此操作!";M_EorrMenage = newString(M_EorrMenage.getBytes("ISO8859_1 "), "GBK");response.setContentType("text/html; charset=gb2312");// out.println("<html>");//out.println("<head><title>no_database</title ></head>");// out.println("<body>");// out.println("<p>" + M_EorrMenage + "</p>");// out.println("</body></html>");}try {if (rs.next()) {in = rs.getBinaryStream("pic");response.reset(); // 返回在流中被标记过的位置response.setContentType("image/jpg"); // 或gif等// int len=in.available();//得到文件大小OutputStream toClient =response.getOutputStream();byte[] P_Buf = new byte[len];int i;while ((i = in.read(P_Buf)) != -1) {toClient.write(P_Buf, 0, i);}in.close();toClient.flush(); // 强制清出缓冲区\\rtoClient.close();} else {M_EorrMenage = "无此图片!";M_EorrMenage = newString(M_EorrMenage.getBytes("ISO8859_1 "),"GBK");response.setContentType("text/html;charset=gb2312");// out.println("<html>");// out// .println("<head><title>this photo isn\'t // have</title></head>");// out.println("<body>");// out.println("<p>" + M_EorrMenage + "</p>");// out.println("</body></html>");}rs.close();} catch (Exception e) {e.printStackTrace();M_EorrMenage = "无法读取图片!";M_EorrMenage = newString(M_EorrMenage.getBytes("ISO8859_1 "), "GBK");response.setContentType("text/html; charset=gb2312");// out// .println("<%@ pagecontentType=\'text/html; charset=gb2312\' // %>");// out.println("<html>");// out.println("<head><title>nophoto</title></head>");// out.println("<body>");// out.println("<p>" + M_EorrMenage + "</p>");// out.println("</body></html>");}try {conn.close();} catch (SQLException e) {e.printStackTrace();}}四、显示图片到页面上在任何想使用图片的页面上使用<img>标签,并把src指向显示图片用的servlet就可以PS:1.addImage 页面,form的ENCTYPE="multipart/form-data"必须这样设置才能正常使用jspSmartUpload组件进行上传,但是这样设置后,无法在下一个页面中通过request.getParameter()获取参数,只能通过mySmartUpload.getRequest().getParameter(p araName)进行参数的获取。