MVC上傳圖檔
V:.jsp
C: .servlet
M:.java
功能一:瀏覽圖檔
.jsp 放置圖片路徑
<div>
<img src="<%=request.getContextPath()%>
/DBGifReader4?
emp_photo_no=${empPhSvc.getAllByEMPNO(empVO.getEmpNo()).get(0).getEmpPhtoNo()}"
</div>
.java從資料庫找圖片
@WebServlet("/DBGifReader4")
public class DBGifReader4 extends HttpServlet {
Connection conn;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("image/gif");
ServletOutputStream out = res.getOutputStream();
req.setCharacterEncoding("UTF-8");
try {
String emp_photo_no = req.getParameter("emp_photo_no");
emp_photo_no = new String(emp_photo_no.getBytes("ISO-8859-1"),"UTF-8");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
"SELECT EMP_PHOTO FROM emp_photos WHERE EMP_PHOTO_NO ='"+emp_photo_no+"'");
if (rs.next()) {
BufferedInputStream in = new BufferedInputStream(rs.getBinaryStream("EMP_PHOTO"));
byte[] buf = new byte[4 * 1024]; // 4K buffer
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
} else {
//res.sendError(HttpServletResponse.SC_NOT_FOUND);
InputStream in = getServletContext().getResourceAsStream("/noData/noPic.jpg");
byte[] b = new byte[in.available()];
in.read(b);
out.write(b);
in.close();
}
rs.close();
stmt.close();
} catch (Exception e) {
System.out.println(e);
InputStream in = getServletContext().getResourceAsStream("/noData/noPic.jpg");
byte[] b = new byte[in.available()];
in.read(b);
out.write(b);
in.close();
}
}
}
功能二:上傳圖檔
.jsp使用form:傳送網頁參數empNo給.servlet
<form>
action="<%=request.getContextPath()%>/employee/employee.do?action=modifySelf"
method="post" id="contact_form" enctype="multipart/form-data">
<input type="hidden" name="empNo" value="${empVO.empNo}">
</form>
.servlet取得String empNo, byte[] empPhoto
if(part.getSize()!=0){
InputStream in = part.getInputStream();
byte[] img = new byte[in.available()];
in.read(img);
EmpPhotosVO empPhotosVO = new EmpPhotosVO();
empPhotosVO.setEmpNo(empNo);//員工編號
empPhotosVO.setEmpPhoto(img);//圖
.servlet將資料傳給.java(service)
empPhotoSvc.updateEmpPhoto(empPhotosVO);
.java(service)將資料傳給.java(dao)
empPhotosVO.getEmpNo();
empPhotosVO.getEmpPhoto();
dao.update(empPhotosVO);
return empPhotosVO;
}
.java(dao)將資料傳給資料庫
pstmt = con.prepareStatement("update emp_photos set EMP_PHOTO = ? where EMP_NO = ?");
pstmt.setBytes(1, EmpPhotos.getEmpPhoto());
pstmt.setString(2, EmpPhotos.getEmpNo());
pstmt.executeUpdate();
資料庫更新資料
功能三:預覽上傳圖檔
.jsp