最近在学习java web,在练习DVD信息管理系统时一直对照片上传问题的处理感到非常棘手,在我的仔细研究和钻研下,终于完美解决了这个难题,下面我讲述一下具体的步骤:
思路阐述:将图片放到项目的/webTest/imgs/文件夹下,为了避免图片名重复,将图片名改为获取当前秒数+ .jpg的格式。然后将图片的项目路径储存到数据库中,以便后面展示图片进行读取图片信息。
需要导入两个jar包:
一.建立实体类和Dao层
/**
* @author Mr Tang
* @version Create Time:2018年10月2日 下午6:39:04
* com.tang.models
*
*/
package com.tang.models;
/**
* @author Mr Tang
*
*/
public class DVDInfoData {
private String dvdnum;
private String dvdname;
private String dvdstate;
private String dvdtype;
private String dvdphoto;
/**
*
*/
public DVDInfoData() {
super();
}
/**
* @param dvdnum
* @param dvdname
* @param dvdstate
* @param dvdtype
* @param dvdphoto
*/
public DVDInfoData(String dvdnum, String dvdname, String dvdstate, String dvdtype, String dvdphoto) {
super();
this.dvdnum = dvdnum;
this.dvdname = dvdname;
this.dvdstate = dvdstate;
this.dvdtype = dvdtype;
this.dvdphoto = dvdphoto;
}
}
package com.tang.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import com.tang.Util.BeanHandler;
import com.tang.Util.BeanListHandler;
import com.tang.Util.JDBCUtil;
import com.tang.models.DVDInfoData;
/**
* @author Mr Tang
* 这个类被用来处理来自数据库的DVD数据,增删改查以及其他功能的实现。
* 继承自DBUtilsBaseDao,简化数据库操作
*/
public class DvdDao extends DBUtilsBaseDao{
/**
* @author Mr Tang
* @throws SQLException
* @expression This method is used to show all DVD information to users.
*It must be do this...
*/
@SuppressWarnings("unchecked")
public static List<DVDInfoData> ShowAllDVD() throws SQLException{
String sql="SELECT * FROM dvddb order by dvdname desc" ;
Object[] params= {};
return (List<DVDInfoData>) JDBCUtil.query(sql, params, new BeanListHandler(DVDInfoData.class));
}
/**
*
*2018年10月21日下午11:38:46
*这个函数的功能是添加DVD信息
*/
public static int addDVD(String dvdNum,String dvdName,String dvdstate,String dvdtype,String dvdphoto) throws SQLException {
int result=0;
if(dvdNum!=""&&dvdName!="") {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
if(pattern.matcher(dvdNum).matches()){
String sql="INSERT INTO dvddb (dvdnum,dvdname,dvdstate,dvdtype,dvdphoto) VALUES (?,?,?,?,?)" ;
Object[] params=new Object[]{
dvdNum,
dvdName,
dvdstate,
dvdtype,
dvdphoto
};
result=JDBCUtil.update(sql, params);
}
}
return result;
}
}
二.创建一个PhotoDao类来处理前台file Input上传的图片资源
/**
* @author Mr Tang
* @version Create Time:2018年10月24日 下午8:22:22
* com.tang.dao
*
*/
package com.tang.dao;
import java.io.File;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* @author Mr Tang
*
*/
public class PhotoDao {
/**
*2018年10月24日下午10:41:33
*这个函数的功能是获取前端的数据集合,将文件打包成File以便后续操作
*/
public static List<FileItem> getRequsetFileItems(HttpServletRequest request,ServletContext servletContext){
boolean isMultipart=ServletFileUpload.isMultipartContent(request);
if(isMultipart) {
DiskFileItemFactory factory = new DiskFileItemFactory();
String str="javax.servelet.context.tempdir";
File repository=(File) servletContext.getAttribute(str);
factory.setRepository(repository);
ServletFileUpload upload=new ServletFileUpload(factory);
try {
return upload.parseRequest(request);
}catch (FileUploadException e) {
// TODO: handle exception
return null;
}
}else {
return null;
}
}
/**
*2018年10月24日下午10:37:59
*这个函数的功能是将文件传到预先设置的绝对路径中,也就是项目里的imgs文件夹
*/
public static boolean saveFile(FileItem item,String fileName) {
File savePath=new File("E:\\Users\\javawebspace\\dvdWeb3.5\\WebContent\\imgs");
if(!savePath.exists()) {
savePath.mkdirs();
}
File uploadFile=new File(savePath+File.separator+fileName);
try{
item.write(uploadFile);
System.out.println("保存文件成功");
return true;
}catch(Exception e){
System.out.println("保存文件失败");
}
return false;
}
/**
*2018年10月24日下午8:02:04
*这个函数的功能是获取当前时间点与1970年的间隔秒数
*/
public static int getSecondTimestamp(Date date){
if (null == date) {
return 0;
}
String timestamp = String.valueOf(date.getTime());
System.out.println(timestamp);
int length = timestamp.length();
if (length > 3) {
return Integer.valueOf(timestamp.substring(0,length-3));
} else {
return 0;
}
}
/**
*
*2018年10月24日下午8:42:05
*这个函数的功能是得到新的照片名称
*/
public static String getPhotoNewName() {
Date date=new Date();
int second=getSecondTimestamp(date);
String fileName=String.valueOf(second)+".jpg";
return fileName;
}
/**
*2018年10月24日下午8:48:58
*这个函数的功能是判断文件后缀是否是jpg格式
*/
public static boolean isGif(FileItem item) {
String fileFullName=item.getName();
File fileInfo=new File(fileFullName);
String suffix = fileInfo.getName().substring(fileInfo.getName().lastIndexOf(".") + 1);
if(suffix.equals("jpg")) {
return true;
}
return false;
}
}
三.创建一个接收图片的jsp前端页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加DVD信息</title>
</head>
<style type="text/css">
table.gridtable {
font-family: verdana, arial, sans-serif;
font-size: 15px;
color: #333333;
border-width: 1px;
border-color: #666666;
border-collapse: collapse;
}
table.gridtable th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #dedede;
}
table.gridtable td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #ffffff;
}
</style>
<script type="text/javascript">
//检查登录表单
function checkBox() {
/* var name = document.getElementById("dvdName").value;
var type = document.getElementById("dvdType").value;
if (name != ""&&type!="") {
return true;
} else {
document.getElementById("isEmpty").value = "EMPTY";
alert("DVD信息不能为空哦~");
document.getElementById("loginname").focus(); //光标占位
return false;
} */
}
</script>
<body>
<div style="margin-left: 400px">
<h1 style="margin-left: 10px;">添加DVD信息:</h1>
<br>
<form method="post"
action="${pageContext.request.contextPath}/ProductServlet?method=add"
enctype="multipart/form-data"
>
<!-- onsubmit=" return checkBox()"
--> <table class="gridtable">
<tr>
<td>编号(已自动分配不可修改):
<div id="myDiv">
</div>
</td>
<td width="300px"><input id="pr_dvdNum" type="text" name="pr_dvdNum"
value="${nextNum }" disabled="disabled"
style="border: 0px; font-size: 20px;">
</td>
</tr>
<tr>
<td>请输入DVD名字:</td>
<td width="300px"><input id="dvdName" type="text"
name="dvdName" style="border: 0px; font-size: 20px;"></td>
</tr>
<tr>
<td>请输入DVD状态:</td>
<td width="300px"><input id="dvdState" type="radio" checked
value="未借出" name="dvdState" style="border: 0px; font-size: 20px;">未借出
<input id="dvdState" type="radio"
value="已借出" name="dvdState" style="border: 0px; font-size: 20px;">已借出
</td>
</tr>
<tr>
<td>请传入DVD图片<br>必须是gif格式</td>
<td><input type="file" name="file"
style="border: 0px; font-size: 20px;"
/></td>
</tr>
<tr>
<td>请输入DVD类型:</td>
<td width="300px"><input id="dvdType" type="text"
name="dvdType" style="border: 0px; font-size: 20px;">
<input type="hidden" name="currentPage" value="${currentPage}">
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="添加"
style="width: 120px; height: 30px; background-color: blue; border: 0px; color: #fff5ee; font-size: 15px; margin-left: 180px;">
<a href="${pageContext.request.contextPath}/ProductServlet?method=toMainView¤tPage=${currentPage }" style="float: right;">返回主页</a></td>
</tr>
</table>
<input type="hidden" id="isEmpty" name="isEmpty" value="FULL">
</form>
</div>
</body>
</html>
四.创建后台处理Servlet服务端
package com.tang.control;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import com.tang.common.Page;
import com.tang.dao.DvdDao;
import com.tang.dao.PhotoDao;
import com.tang.dao.UserDao;
import com.tang.models.DVDInfoData;
/**
* @author Mr Tang
*
*/
@WebServlet("/ProductServlet")
public class ProductServlet extends HttpServlet {
public ProductServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("method");
try {
switch (method) {
case "add":
//转接给相对应的函数去处理相关数据。
addDVDinfo(request, response);
break;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* <p>
* 这个函数实现了增加dvd的功能
* <p>
* @throws SQLException
* @throws ServletException
*/
private static void addDVDinfo(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
List<String> list=new ArrayList<String>();
String filename=PhotoDao.getPhotoNewName();
ServletContext servletContext=null;
servletContext=request.getSession().getServletContext();
//数据库中存储格式:/webTest/imgs/***.jpg
//第一步:获取页面上上传的图片资源
List<FileItem> items=PhotoDao.getRequsetFileItems(request,servletContext);
boolean isLoadToSQL=false;
for(FileItem item:items) {
if(!item.isFormField()){
//判断后缀名是否是jpg
if(PhotoDao.isGif(item)) {
isLoadToSQL=PhotoDao.saveFile(item,filename);
}else {
System.out.println("后缀格式有误,保存文件失败");
}
}else {
/*获取表单中的非文件值
表单中的空间name值
System.out.println("name值: "+item.getFieldName());
该name值空间中的value值
System.out.println(item.getString("UTF-8"));*/
list.add(item.getString("UTF-8"));
}
}
String dvdNum=DvdDao.returnNextNum();
//存在数据库里面的照片路径是在项目里的相对路径
String finalPhotoName= request.getContextPath()+"/imgs/"+filename;
int bol=DvdDao.addDVD(dvdNum, "《"+list.get(0)+"》",list.get(1),list.get(2),finalPhotoName);
if(list.get(4).equals("FULL")) {
if(bol>0) {
PrintWriter out=response.getWriter();
out.flush();
out.print("<script>");
out.println("alert('添加DVD信息成功!!!')");
out.print("window.location.href='ProductServlet?method=toAddView¤tPage=");
out.print(list.get(3)); /*第四个数下标为3表示主页的页数*/
out.print("'</script>\");");
out.close();
}else {
PrintWriter out=response.getWriter();
out.flush();
out.print("<script>");
out.println("alert('很抱歉,添加DVD失败,请检查填入信息是否正确!!!')");
out.println("history.back();");
out.println("</script>");
out.close();
}
}
else if(list.get(4).equals("EMPTY")){
PrintWriter out=response.getWriter();
out.flush();
out.print("<script>");
out.print("window.location.href='ProductServlet?method=toAddView';");
out.println("</script>");
out.close();
}
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
五.结果展示