图像文件上传数据库

 代码:

 index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>文件上传</title>
</head>
<body>
   <form action="FileUploadServlet" method="post" enctype="multipart/form-data">
               选择上传文件:
     <input type="file" name="file" id="file" accept="image/*"/><br/><br/>
     <input type="submit" value="上传" name="upload" id="upload"/>
   </form>
</body>
</html>

FileUploadServlet.java

package com.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.connect.DButil;
@MultipartConfig//标识Servlet支持文件上传
public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public FileUploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    protected void processRequest(HttpServletRequest request,HttpServletResponse response)
    		throws ServletException,IOException{
    	response.setContentType("text/html;charset=UTF-8");
    	request.setCharacterEncoding("UTF-8");
    	
        final Part filePart=request.getPart("file");
    	final String fileName=getFileName(filePart);
    	Connection conn=null;
    	
    	OutputStream out=null;
    	InputStream filecontent=null;
    	final PrintWriter writer=response.getWriter();
    	
    	try {
    		conn=DButil.open();
			conn.setAutoCommit(false);
			
			String sql="INSERT INTO images(name,image) VALUES(?,?)";
			PreparedStatement stmt=(PreparedStatement) conn.prepareStatement(sql);
			stmt.setString(1, fileName);
			filecontent=filePart.getInputStream();
			
			stmt.setBinaryStream(2, filecontent, (int)filePart.getSize());
			stmt.execute();
			
			conn.commit();
			response.sendRedirect("disping.jsp");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			writer.println("<br/>错误:"+e.getMessage());
			e.printStackTrace();
		}
    	finally {
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(out!=null){
				out.close();
			}
			if(filecontent!=null){
				filecontent.close();
			}
			if(writer!=null){
				writer.close();
			}
		}
    	
    }
	private String getFileName(final Part part) {
		// TODO Auto-generated method stub
		for(String content : part.getHeader("content-disposition").split(";")){
			String filename=content.substring(content.lastIndexOf('\\')+1).trim().replace("\"", "");
			return filename;
		}
		return null;
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}

disping.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>显示最后一张图片</title>
</head>
<body>
     <h4>显示最后一张图片</h4>
     <img alt="图片" src="ImageServlet"/>
</body>
</html>

ImageServlet.java

package com.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.connect.DButil;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public ImageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("image/jpeg");
		request.setCharacterEncoding("UTF-8");
		ServletOutputStream os=response.getOutputStream();
		
		Connection conn=null;
		
		try {
			conn=DButil.open();
			String sql="SELECT name,image FROM images ORDER BY id DESC";
			PreparedStatement stmt=(PreparedStatement) conn.prepareStatement(sql);
			ResultSet rs=stmt.executeQuery();
			if(rs.next()){
				//没有用到
				@SuppressWarnings("unused")
			  String name=rs.getString(1);
			  
			  byte[] buffer=new byte[1];
			  InputStream is=rs.getBinaryStream(2);
			  while(is.read(buffer)>0){
				  os.write(buffer);
			  }
			  os.flush();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(os!=null){
				os.close();
			}
		}
		
	}

}

截图:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潇潇雨歇_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值