您的位置:首页 > Web前端 > JavaScript

jsp+servlet+二进制图片存取

2017-07-31 16:18 225 查看
前段时间做了一个有关图片存取数据库的小项目,虽然本人是个小菜鸟,但在我不断地努力下,嘿嘿,很快做了出来,所然我用的方法是采用二进制存入数据库,然后返回list,在jsp页面显示了出来。

好了,废话不多说了,下面贴代码!~^O^~

一、创建数据库



二、表单提交存入数据库:

JSP页面(上传到相应的servlet)

// ENCTYPE="multipart/form-data"用于表单里有图片上传。
<form action="${pageContext.request.contextPath}/CaptialServlet" method="post" enctype="multipart/form-data">
<input hidden="hidden" name="date" type="text" value=<%=date%>></input>
<input hidden="hidden" name="author" type="text" value=<%=username%>></input>
<h1>文章发布</h1>
<label>
<span>文章标题:</span>
<input type="text" name="article"/>
</label>
<label>
<span>文章内容:</span>
<textarea name="content" ></textarea>
</label>
<label>
<span>选择插入图片:</span>
<input type="file" accept="image/*" name="picture"/>	// 输入字段可以接受各种格式的图片
</label>
<label>
<span> </span>
<input type="submit" class="button" value="发送" />
</label>
</form>

Servlet(处理表单提交的数据)

public class CaptialServlet extends HttpServlet {
private static final long serialVersionUID = 1L;	// 为了在反序列化时,确保类版本的兼容性
private String savePath;
private ServletContext sc;

public void init(ServletConfig config) {
savePath="upload";		//得到上传文件的保存目录,将上传的文件存放于服务器项目根目录下(需要自己创建)
sc = config.getServletContext(); // 获取上下文
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
Map<String, String> map=new HashMap<>();	// 用于存储表单非二进制流部分
boolean isMultipart = ServletFileUpload.isMultipartContent(request);// 检查输入请求是否为multipart表单数据。
if (isMultipart == true) {   // 如果是二进制流形式的表单
FileItemFactory factory = new DiskFileItemFactory();// 通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
File savedFile=null;
try {
items = upload.parseRequest(request);	// 可以上传多个文件
} catch (FileUploadException e) {
// TODO Auto-generated
4000
catch block
e.printStackTrace();
}
Iterator<FileItem> itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();

if (item.isFormField()) {//检测是否为普通表单 如果是普通表单项目,将其名字与对应的value值放入map中。
String fieldName = item.getFieldName();
map.put(fieldName, item.getString("UTF-8"));//获取表单value时确定数据格式,如果不写,有中文的话会乱码

} else {   //如果是提交的图片
File fullFile=new File(item.getName()); //获取提交的文件
savedFile=new File(sc.getRealPath("/")+savePath,fullFile.getName()); //在项目下新建该文件,
try {
item.write(savedFile); //写入文件

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
out.println("  Map"+map.toString());
out.println("<br/>");
out.println(map.get("article")+" " + map.get("content")+" " + map.get("author")+" " + map.get("date")+" " + null);
FileInputStream str=new FileInputStream(savedFile);//将保存的文件转换为输入流
int length=str.available();//获取输入流的长度;
//下面是我将自己的普通表单内容放到captial对象中
Captial captial=new Captial(0, map.get("article"), map.get("content"), map.get("date"), map.get("author"), null);
UserDao userDao=new UserDao();
boolean flag=userDao.input(captial,str,length);//这步是将captial对象,输入流,和输入流的长度传到 userdao的addUser方法中 用于添加到数据库;
if(flag){
response.sendRedirect("/businessShow.jsp");
}else{
response.getWriter().print("<script type=\"text/javascript\">alert(\"添加失败,图片限制大小为200*169像素\");location.href(\"/input.jsp\");</script>");
}
} else {
out.print("the enctype must be multipart/form-data");
}
}

}

UserDao(Dao层操作)

public class UserDao {

User user = null;
private String SQL ="";

// 查询出发布文章的相关信息,便于展示在jsp页面
public List<Captial> show(){
SQL = "select * from captial";
Connection connection = null;
PreparedStatement pstmt = null;
Captial captial;
List<Captial> list = new ArrayList<Captial>();	// 获取数据库字段集
try {
connection = DBDao.getConnection();
pstmt = (PreparedStatement) connection.prepareStatement(SQL);
ResultSet rs = (ResultSet) pstmt.executeQuery();//得到数据库的查询结果,一个数据集
while(rs.next()){
captial = new Captial();
captial.setId(rs.getInt("id"));
captial.setArticle(rs.getString("article"));
captial.setContent(rs.getString("content"));
captial.setDate(rs.getString("date"));
captial.setAuthor(rs.getString("author"));
list.add(captial);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
// 根据id查询图片
public ResultSet show(int id){
SQL = "select picture from captial where id = ?";
Connection connection = null;
PreparedStatement pstmt = null;
try {
connection = DBDao.getConnection();
pstmt = (PreparedStatement)     connection.prepareStatement(SQL);
pstmt.setInt(1, id);
ResultSet rs = (ResultSet) pstmt.executeQuery();//得到数据库的查询结果,一个数据集
return rs;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

// 提交表单数据
public boolean input(Captial captial,FileInputStream file,int length){
boolean flag=true;
String SQL = "insert into captial(article,content,date,author,picture) values(?,?,?,?,?)";
Connection connection = null;
PreparedStatement pstmt = null;
try {
connection = DBDao.getConnection();
pstmt = (PreparedStatement)connection.prepareStatement(SQL);
//这里的意思将用户名和密码填到SQL语句的问号处
pstmt.setString(1, captial.getArticle());
pstmt.setString(2, captial.getContent());
pstmt.setString(3, captial.getDate());
pstmt.setString(4, captial.getAuthor());
pstmt.setBinaryStream(5, file,length);
flag = pstmt.execute();
connection.close();
pstmt.close();
return flag;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return !flag;
}finally{
DBDao.closeConnection(connection);
}
}
}

JDBC连接

public class DBDao {
private static String USER = "root";
private static String PASSWORD = "root";
private static String DB_URL = "jdbc:mysql://localhost:3306/university";
private static String DB_DRIVER = "com.mysql.jdbc.Driver";
private static Connection connection = null;

public static Connection getConnection(){

try {
Class.forName(DB_DRIVER);
connection = DriverManager.getConnection(DB_URL, USER, PASSWORD);
} catch (Exception e) {
System.out.println("数据库连接异常");
e.printStackTrace();
}
return connection;
}
public  static void closeConnection(Connection connection){

if(connection != null){
try {
connection.close(); // 关闭数据库连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
这样,提交的表单就传进数据库了

三、取出数据库数据,并显示在jsp上

Dao层操作为上面的show()和show(id)方法

Servlet(将二进制图片显示出来)

public class BusinessShowPicture extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int id = Integer.parseInt(request.getParameter("id"));
UserDao userDao = new UserDao();
ResultSet rs = userDao.show(id);
InputStream in = null;
OutputStream out = response.getOutputStream();
try {
while(rs.next()){
Blob blob = rs.getBlob("picture");
in = blob.getBinaryStream();

byte[] blobBuffer = new byte[1024*4];
int length = 0;
while((length=in.read(blobBuffer))!= -1){
out.write(blobBuffer,0,length);
}
in.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

jsp显示

<%
UserDao userDao = new UserDao();
List<Captial> list = userDao.show();
for(Captial captial:list){
%>
<div class="" style="min-height:169px !important">
<!-- img -->
<div class="img left">
<img src="${pageContext.request.contextPath}/BusinessShowPicture?id=<%=captial.getId() %>" alt="" title=""/>
</div>

<div class="block right">
<p class="date"><%=captial.getDate()%></p>
<p class="title"><%=captial.getArticle() %></p>
<p class="content"><%=captial.getContent() %></p>
</div>
</div>
<%} %>


             

这样,就完成了!

偶,对了,还有在web.xml配置相应servlet,以及commons-fileupload-1.2.1.jar、commons-io-1.4.jar和mysql-connector-java-5.1.25-bin.jar导入
-----真正完成了!o(*≧▽≦)ツ

下面是完成图啦

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: