iLeichun

当前位置: 首页 > 个人日志

Java Servlet将图片保存到数据库

分类:个人日志   来源:原创   时间:2011-06-02 23:17:23

/*
 * 为了提高速度,我们常将图片保存到文件夹下。
 * 本文将为您介绍在Java中如何将图片保存到数据库,使用了Servlet先将图片转换为二进制,再将二进制图片数据保存到数据库。 
 */

package com.kancool.base.service.support;

import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import com.kancool.base.dao.support.*;

public class BasicAddImageServiceSupport extends HttpServlet {

 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  PrintWriter out = response.getWriter();
  try{
   Class.forName("com.mysql.jdbc.Driver");
   Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/cool","root","mysql");
   String imageTitle=new String((request.getParameter("iamgetitle")).getBytes("ISO-8859-1"),"gb2312");
   String image=new String((request.getParameter("image")).getBytes("ISO-8859-1"),"gb2312");
   FileInputStream ima=new FileInputStream(image);
   String sql="insert into images(image,title) values(?,?)";
   PreparedStatement pstmt=conn.prepareStatement(sql);
   pstmt.setBinaryStream(1,ima,ima.available());
   pstmt.setString(2,imageTitle);
   pstmt.executeUpdate();
   out.print("success!");
  }catch(Exception e){
   e.getStackTrace();
  }
 
 }

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doGet(request,response);
 }

}

 

更多