package imgdemo; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import utils.Base64; import utils.StringUtil; @SuppressWarnings("all") public class ImgServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String img = getImgById(); byte[] decode = Base64.decode(img); OutputStream outputStream = response.getOutputStream(); outputStream.write(decode); } catch (Exception e) { e.printStackTrace(); } } public void init() throws ServletException { } public static ResultSet rs = null; public static void main(String[] args) throws Exception { insertImgDb(); // getImgById(); } public static void insertImgDb() throws Exception{ File f = new File("D:\\123.jpg"); System.out.println("s"); Connection conn = JdbcUtils.getConnection(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String id = sdf.format(new Date()); System.out.println(id); String sql = "insert into imgdemo (id,image) values(?,?)"; PreparedStatement pst = conn.prepareStatement(sql); InputStream is = new FileInputStream(f); String img = Base64.encode(is); System.out.println(img); pst.setString(1, id); pst.setString(2, img); pst.execute(); conn.commit(); JdbcUtils.free(rs, pst, conn); } public static String getImgById() throws Exception{ System.out.println(new String("20170812171808052").length()); Connection conn = JdbcUtils.getConnection(); String sql = "select t.image from imgdemo t where id = ? "; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1, "20170812174713600"); rs = pst.executeQuery(); Object img = ""; while (rs.next()) { img = rs.getObject(1); } String clob2String = StringUtil.getClob2String(img); System.out.println(clob2String); JdbcUtils.free(rs, pst, conn); return clob2String; } }
最近下载更多