jsp把图片写到数据库的代码,多种写法

由于要做上传 就找了个例子 留着参考

 

上传:需要smartupload组件  

 

import com.jspsmart.upload.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; /** * 上传公共类,对SmartUpload进行了封装 * @author askr * @version 1.0 */ public class MyUpload { /** *保存上传的文件 * * @param request 页面请求对象 * @param response 页面响应对象 * @param config 页面配置对象 * @param mainName 赋予的主文件名 * @param savePhyPath 文件保存的文件夹 * @param maxSizePool 上传时允许的最大容量,单位:KB * @param maxSizeAllowed 文件上传时允许的最大大小,单位:KB * @param formatListAllowed 允许的文件格式,以逗号分隔的字符串序列 * @return 如果没有上传,返回空字符串,否则,是保存后的文件名 */ public static String SaveUpload(HttpServletRequest request, HttpServletResponse response,ServletConfig config, String mainName,String savePhyPath,int maxSizePool,int maxSizeAllowed, String formatListAllowed) { SmartUpload upl = new SmartUpload(); com.jspsmart.upload.File f=null; try { upl.init(config); //config是隐含内置对象 upl.service(request, response); // upl.setAllowedFilesList(formatListAllowed); upl.setTotalMaxFileSize(maxSizePool * 1024); //字节 upl.upload(); f = upl.getFiles().getFile(0); String name = f.getFileName(); if (f.getSize() == 0) { return ""; } if (f.getSize() > maxSizeAllowed * 1024) throw new RuntimeException("最大大小为" + maxSizeAllowed + "KB"); String ext=f.getFileExt(); StringTokenizer st=new StringTokenizer(formatListAllowed,","); boolean formatFlag=false; while (st.hasMoreTokens()) { String element=st.nextToken(); if (element.equalsIgnoreCase(ext)) { formatFlag = true; break; } } if (formatFlag==false) throw new RuntimeException("文件格式不对,必须是"+ formatListAllowed+"中的一种"); String path = savePhyPath + "//" + mainName + "." + f.getFileExt(); f.saveAs(path,com.jspsmart.upload.File.SAVEAS_PHYSICAL); } catch (RuntimeException ex) { throw ex; } catch(IOException ex) { ex.printStackTrace(); } catch (SmartUploadException ex) { ex.printStackTrace(); } catch (ServletException ex) { ex.printStackTrace(); } return mainName + "." +f.getFileExt(); } } 生成缩略图: import com.sun.image.codec.jpeg.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.*; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class CompressImage { /** * * @param oldPath:需要压缩的文件完整物理路径,包括名字 * @param newDir:新文件的保存路径,不含名字 * @param newMainName 新文件的主文件名 * @param maxBorder 新文件的长度和宽度里面最长的边的长度,按比例缩小另外的一个边,比如要生成 * 的图形最长的边是64像素,如果是长度比宽度大,那么,生成的长度是64,而宽度就是原始的宽度的等比例缩小的尺寸。 */ public static void Generate(String oldPath,String newDir,String newMainName,int maxBorder) { File souFile=new File(oldPath); // String a=souFile.getAbsolutePath(); // int a1=1; try { String newPath; if (newDir.equals("")) newPath = newMainName + ".jpg"; else newPath =newDir + "//" + newMainName + ".jpg"; FileOutputStream desFile = new FileOutputStream(new File(newPath)); BufferedImage souImage = ImageIO.read(souFile); int oldWidth = souImage.getWidth(); int oldHeight = souImage.getHeight(); int newWidth, newHeight; if (oldWidth > oldHeight) { newWidth = maxBorder; newHeight = (int) (newWidth * oldHeight / oldWidth); } else { newHeight = maxBorder; newWidth = (int) (oldWidth * newHeight / oldHeight); } BufferedImage desImage = new BufferedImage( newWidth, newHeight,1); desImage.getGraphics().drawImage(souImage,0,0,newWidth,newHeight, null); JPEGImageEncoder jpegEncode = JPEGCodec.createJPEGEncoder(desFile); jpegEncode.encode(desImage); desFile.close(); } catch (ImageFormatException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } ///////////////////////////////////////////////////////////////////////servlet方法如下: javabean: mport java.io.*; public class dbo { public dbo() { } public InputStream getBytes() { Connection con = null; PreparedStatement pst = null; ResultSet rs = null; InputStream stream = null; File f = null; byte context[] = new byte[100000]; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:test"); f = new File("C://aa.jpg"); stream = new FileInputStream(f); //pst = con.prepareStatement("INSERT INTO MyTable (COL10) VALUES(?)"); //pst.setBinaryStream(1,stream,(int)f.length()); pst = con.prepareStatement("SELECT COL10 FROM MyTable"); rs = pst.executeQuery(); if (rs.next()) { stream = rs.getBinaryStream(1); } return stream; } catch (Exception e) { System.out.println(e); return stream; } finally { try { /* if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { pst.close(); } */ } catch (Exception e) { } } } public static void main(String args[]) { } } /* 写入数据库 Connection con = null; PreparedStatement pst = null; ResultSet rs = null; InputStream stream = null; File f=null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:test"); f = new File("C://aa.jpg"); stream = new FileInputStream(f); pst = con.prepareStatement("INSERT INTO MyTable (COL10) VALUES(?)"); pst.setBinaryStream(1,stream,(int)f.length()); pst.execute(); } catch (Exception e) { System.out.println(e); } finally { try { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { pst.close(); } } catch (Exception e) { } } */ jsp and servlet jsp: <%@ page contentType="text/html; charset=GBK" %> <html> <head> <title> jsp1 </title> </head> <body bgcolor="#ffffff"> dfdfd <img src="servlet1?id=1" mce_src="servlet1?id=1"/> dfdef </body> </html> servlet: package index; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; //import java.util.*; import index.dbo; public class Servlet1 extends HttpServlet { private static final String CONTENT_TYPE = "text/html; charset=GBK"; //Initialize global variables public void init() throws ServletException { } //Process the HTTP Get request public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.setContentType("image/gif;"); dbo d = new dbo(); java.io.InputStream pic = null; java.io.OutputStream pw = null; try{ //request.getParameter("id"); response.setContentType("image/gif;name=doskt.jpg"); pic=d.getBytes(); pw=response.getOutputStream(); byte[] b = new byte[4096]; int bt = pic.read(b); while (bt != -1) { pw.write(b, 0, bt); bt = pic.read(b); } } catch(Exception e){ System.out.println("doGet:" + e); } finally{ if(pic!=null){ pic.close(); } } /*out.println("<html>"); out.println("<head><title>Servlet1</title></head>"); out.println("<body bgcolor=/"#ffffff/">"); out.println("<p>The servlet has received a GET. This is the reply.</p>"); out.println("</body></html>");*/ } //Clean up resources public void destroy() { } } 文章出处:DIY部落(http://www.diybl.com/course/4_webprogram/jsp/jsp_js/2008430/112053_4.html)

你可能感兴趣的:(jsp,exception,数据库,String,null,import)