日期:2014-05-16 浏览次数:20521 次
package demo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import demo.sql.DaoTest;
public class LoadPicture extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
DaoTest dt=new DaoTest();
Connection conn = dt.getConn();
String sql = "select t.content from filetest t where t.name='最终图片测试'";
PreparedStatement ps = null;
ResultSet rs = null;
InputStream is = null;
ServletOutputStream os = null;
OutputStream out=null;
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()) {
is = rs.getBinaryStream(1);
}
File file=new File("c://abc.jpg");
out=new FileOutputStream(file);
resp.setContentType("image/jpeg");
os = resp.getOutputStream();
int num;
byte buf[] = new byte[1024];
while ((num = is.read(buf)) != -1) {
os.write(buf, 0, num);
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
is.close();
os.close();
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <img name="pic" src="<%=basePath+"loadPicture.action"%>"/> </body> </html>