java web 将图像上传到项目目录,并将文件路径输入数据库
最编程
2024-03-23 18:04:28
...
最近在学习java web,在练习DVD信息管理系统时一直对照片上传问题的处理感到非常棘手,在我的仔细研究和钻研下,终于完美解决了这个难题,下面我讲述一下具体的步骤:
思路阐述:将图片放到项目的/webTest/imgs/文件夹下,为了避免图片名重复,将图片名改为获取当前秒数+ .jpg的格式。然后将图片的项目路径储存到数据库中,以便后面展示图片进行读取图片信息。
第一步:准备工作
环境要求
1. 开发环境: Eclipse
2.导入两个文件上传的jar包
3 MySQL平台,我用的是dbForge Studio for MySQL。
第二步 创建一个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前端页面
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() 6 + path + "/"; 7 %> 8 <!DOCTYPE html> 9 <html> 10 <head> 11 <meta charset="UTF-8"> 12 <title>添加DVD信息</title> 13 </head> 14 <style type="text/css"> 15 table.gridtable { 16 font-family: verdana, arial, sans-serif; 17 font-size: 15px; 18 color: #333333; 19 border-width: 1px; 20 border-color: #666666; 21 border-collapse: collapse; 22 } 23 24 table.gridtable th { 25 border-width: 1px; 26 padding: 8px; 27 border-style: solid; 28 border-color: #666666; 29 background-color: #dedede; 30 } 31 32 table.gridtable td { 33 border-width: 1px; 34 padding: 8px; 35 border-style: solid; 36 border-color: #666666; 37 background-color: #ffffff; 38 } 39 </style> 40 <script type="text/javascript"> 41 //检查登录表单 42 function checkBox() { 43 /* var name = document.getElementById("dvdName").value; 44 var type = document.getElementById("dvdType").value; 45 46 if (name != ""&&type!="") { 47 return true; 48 } else { 49 document.getElementById("isEmpty").value = "EMPTY"; 50 alert("DVD信息不能为空哦~"); 51 document.getElementById("loginname").focus(); //光标占位 52 return false; 53 } */ 54 } 55 </script> 56 <body> 57 <div style="margin-left: 400px"> 58 <h1 style="margin-left: 10px;">添加DVD信息:</h1> 59 <br> 60 <form method="post" 61 action="${pageContext.request.contextPath}/ProductServlet?method=add" 62 enctype="multipart/form-data" 63 > 64 <!-- onsubmit=" return checkBox()" 65 --> <table class="gridtable"> 66 <tr> 67 <td>编号(已自动分配不可修改): 68 <div id="myDiv"> 69 </div> 70 </td> 71 <td width="300px"><input id="pr_dvdNum" type="text" name="pr_dvdNum" 72 value="${nextNum }" disabled="disabled" 73 style="border: 0px; font-size: 20px;"> 74 </td> 75 </tr> 76 <tr> 77 <td>请输入DVD名字:</td> 78 <td width="300px"><input id="dvdName" type="text" 79 name="dvdName" style="border: 0px; font-size: 20px;"></td> 80 </tr> 81 <tr> 82 <td>请输入DVD状态:</td> 83 <td width="300px"><input id="dvdState" type="radio" checked 84 value="未借出" name="dvdState" style="border: 0px; font-size: 20px;">未借出 85 <input id="dvdState" type="radio" 86 value="已借出" name="dvdState" style="border: 0px; font-size: 20px;">已借出 87 </td> 88 </tr> 89 <tr>
90 <td>请传入DVD图片<br>必须是gif格式</td> 91 <td><input type="file" name="file" 92 style="border: 0px; font-size: 20px;" 93 /></td>
94 </tr> 95 <tr> 96 <td>请输入DVD类型:</td> 97 <td width="300px"><input id="dvdType" type="text" 98 name="dvdType" style="border: 0px; font-size: 20px;"> 99 <input type="hidden" name="currentPage" value="${currentPage}"> 100 101 </td> 102 </tr> 103 <tr> 104 105 <td colspan="2"><input type="submit" value="添加" 106 style="width: 120px; height: 30px; background-color: blue; border: 0px; color: #fff5ee; font-size: 15px; margin-left: 180px;"> 107 <a href="${pageContext.request.contextPath}/ProductServlet?method=toMainView¤tPage=${currentPage }" style="float: right;">返回主页</a></td> 108 </tr> 109 </table> 110 <input type="hidden" id="isEmpty" name="isEmpty" value="FULL"> 111 </form> 112 </div> 113 </body> 114 </html>
说明:由于我是直接把项目中的整个jsp页面展示出来了,所以只需注意红色的部分就可以了。
第四步 创建后台处理Servlet服务端
1 package com.tang.control; 2 import java.io.IOException; 3 import java.io.PrintWriter; 4 import java.sql.SQLException; 5 import java.util.ArrayList; 6 import java.util.List; 7 8 import javax.servlet.ServletContext; 9 import javax.servlet.ServletException; 10 import javax.servlet.annotation.WebServlet; 11 import javax.servlet.http.HttpServlet; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 import javax.servlet.http.HttpSession; 15 16 import org.apache.commons.fileupload.FileItem; 17 18 import com.tang.common.Page; 19 import com.tang.dao.DvdDao; 20 import com.tang.dao.PhotoDao; 21 import com.tang.dao.UserDao; 22 import com.tang.models.DVDInfoData; 23 24 /** 25 * @author Mr Tang 26 * 27 */ 28 @WebServlet("/ProductServlet") 29 public class ProductServlet extends HttpServlet { 30 public ProductServlet() { 31 super(); 32 } 33 protected void doGet(HttpServletRequest request, 34 HttpServletResponse response) throws ServletException, IOException { 35 String method = request.getParameter("method"); 36 try { 37 switch (method) { 38 case "add": 39 //转接给相对应的函数去处理相关数据。 40 addDVDinfo(request, response); 41 break; 42 } catch (SQLException e) { 43 // TODO Auto-generated catch block 44 e.printStackTrace(); 45 } 46 } 47 /** 48 * <p> 49 * 这个函数实现了增加dvd的功能 50 * <p> 51 * @throws SQLException 52 * @throws ServletException 53 */ 54 private static void addDVDinfo(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException { 55 List<String> list=new ArrayList<String>(); 56 String filename=PhotoDao.getPhotoNewName(); 57 ServletContext servletContext=null; 58 servletContext=request.getSession().getServletContext(); 59 //数据库中存储格式:/webTest/imgs/***.jpg 60 //第一步:获取页面上上传的图片资源 61 List<FileItem> items=PhotoDao.getRequsetFileItems(request,servletContext); 62 boolean isLoadToSQL=false; 63 for(FileItem item:items) { 64 if(!item.isFormField()){ 65 //判断后缀名是否是jpg 66 if(PhotoDao.isGif(item)) { 67 isLoadToSQL=PhotoDao.saveFile(item,filename); 68 }else { 69 System.out.println("后缀格式有误,保存文件失败"); 70 } 71 }else { 72 /*获取表单中的非文件值 73 表单中的空间name值 74 System.out.println("name值: "+item.getFieldName()); 75 该name值空间中的value值 76 System.out.println(item.getString("UTF-8"));*/ 77 list.add(item.getString("UTF-8")); 78 } 79 } 80 String dvdNum=DvdDao.returnNextNum(); 81 //存在数据库里面的照片路径是在项目里的相对路径 82 String finalPhotoName= request.getContextPath()+"/imgs/"+filename; 83 int bol=DvdDao.addDVD(dvdNum, "《"+list.get(0)+"》",list.get(1),list.get(2),finalPhotoName); 84 if(list.get(4).equals("FULL")) { 85 if(bol>0) { 86 PrintWriter out=response.getWriter(); 87 out.flush(); 88 out.print("<script>"); 89 out.println("alert('添加DVD信息成功!!!')"); 90 out.print("window.location.href='ProductServlet?method=toAddView¤tPage="); 91 out.print(list.get(3)); /*第四个数下标为3表示主页的页数*/ 92 out.print("'</script>\");"); 93 out.close(); 94 }else { 95 PrintWriter out=response.getWriter(); 96 out.flush(); 97 out.print("<script>"); 98 out.println("alert('很抱歉,添加DVD失败,请检查填入信息是否正确!!!')"); 99 out.println("history.back();"); 100 out.println("</script>"); 101 out.close(); 102 } 103 } 104 else if(list.get(4).equals("EMPTY")){ 105 PrintWriter out=response.getWriter(); 106 out.flush(); 107 out.print("<script>"); 108 out.print("window.location.href='ProductServlet?method=toAddView';"); 109 out.println("</script>"); 110 out.close(); 111 } 112 } 113 protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { 114 doGet(request, response); 115 } 116 }
说明:由于我是直接把项目中的整个ProductServlet页面展示出来了,所以只需注意红色和蓝色的部分就可以了。红色部分的代码实现了文件存储在项目文件里,蓝色部分实现了将dvd实例化的对象存储到数据库中。
第五步:结果展示
附加:DVDInfoData.java 文件 和DvdDao.java 文件。(第一个是对DVD信息的封装,第二个是把dvd信息存储到数据库中)
/** * @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; } }