我的jsp页面表单如下:
<form name="form1" action="/YiQu/AddUserServlet?jurisdiction=1" method="post" enctype="multipart/form-data"> <table align="center"> <tr> <td>用户id:</td> <td><input type="text" name="userid" ></td> </tr> <tr> <td>用户名:</td> <td><input type="text" name="username" ></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="userpassword" ></td> </tr> <tr> <td>昵称:</td> <td><input type="text" name="usernickname" ></td> </tr> <tr> <td>头像:</td> <td><input type="file" name="userpicture" accept="image/*"></td> </tr> <tr> <td>个性签名:</td> <td><input type="text" name="userdescription" ></td> </tr> <tr> <td>mabeyuse:</td> <td><input type="text" name="mabeyuse" ></td> </tr> <tr> <td>生日:</td> <td><input type="date" name="userdate" ></td> </tr> <tr> <td>性别:</td> <td><input type="radio" name="usersex" value="男" checked>男 <input type="radio" name="usersex" value="女" >女</td> </tr> <tr> <td>地址:</td> <td><input type="text" name="useraddr" ></td> </tr> <tr> <td>邮箱:</td> <td><input type="text" name="usermail" ></td> </tr> <tr> <td>电话:</td> <td><input type="text" name="usertel" ></td> </tr> <tr> <td>支付宝:</td> <td><input type="text" name="useralipayid" ></td> </tr> <tr> <td>权限:</td> <td><input type="text" name="jurisdiction" ></td> </tr> <tr> <td></td> <td><input type="submit" value="添加"></td> </tr> </table> </form> </body>
我想要后台提取file标签上传的图片,然后存到mysql数据库,一开始我使用默认方式进行提交表单,发现只能获取file标签上传图片的名字,并不能获取图片内容,
那么我就要将表单以二进制流的形式进行提交,
表单默认:enctype="application/x-www-form-urlencoded",
我需要将它改为:enctype="multipart/form-data",这时候提交的表单就是二进制流数据,
既然是以数据流上传,那么后台request.getParameter("")获取不到数据,只有经过解析后获取标签内容,
这里要用到Apache的commons-fileupload.jar 然而这个jar包基于commons-io.jar ,所以要导入这两个jar包:
导入之后编写后台接收servlet
我的servlet如下:
public class AddUserServlet 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) */ 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 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(" username="+map.get("username")); out.println(map.get("userid")+" "+ map.get("username")+" "+ map.get("userpassword")+" "+map.get("usernickname")+" "+null+" "+map.get("userdescription")+" "+map.get("mabeyuse")+" "+Date.valueOf("".equals(map.get("userdate"))?"2012-1-1":map.get("userdate"))+" "+map.get("usersex")+" "+map.get("useraddr")+" "+map.get("usermail")+" "+map.get("usertel")+" "+ map.get("useralipayid")+" "+ map.get("jurisdiction")); FileInputStream str=new FileInputStream(savedFile);//将保存的文件转换为输入流 int length=str.available();//获取输入流的长度; //下面是我将自己的普通表单内容放到User对象中 User user=new User(0, map.get("username"), map.get("userpassword"), map.get("usernickname"), null, map.get("userdescription"), Integer.parseInt(map.get("mabeyuse")==""?"0":map.get("mabeyuse")), Date.valueOf("".equals(map.get("userdate"))?"2012-1-1":map.get("userdate")), map.get("usersex"), map.get("useraddr"), map.get("usermail"), map.get("usertel"), map.get("useralipayid"), Integer.parseInt(map.get("jurisdiction")==""?"0":map.get("jurisdiction"))); UserDao userDao=new UserDaoImpl(); boolean flag=userDao.addUser(user,str,length);//这步是将user对象,输入流,和输入流的长度传到 userdao的addUser方法中 用于添加到数据库; if(flag){ response.sendRedirect("/xxx/UserServlet"); }else{ response.getWriter().print("<script type=\"text/javascript\">alert(\"添加失败\");location.href(\"/xxx/addUser.jsp\");</>"); } } else { out.print("the enctype must be multipart/form-data"); } } }
我的addUser方法如下:
//插如数据库操作,主要是 pst.setBinaryStream(4,file,length);将输入流存入数据库blob类型数据中public boolean updateUser(User user,FileInputStream file,int length) { boolean flag=true; String sql="update user set username=? ,"+" userpassword=? ," +" usernickname=? ," +" userpicture=? ," +" userdescription=? ," +" mabeyuse=? ," +" userdate=? ," +" usersex=? ," +" useraddr=? ," +" usermail=? ," +" usertel=? ," +" useralipayid=? ," +" jurisdiction=? " +"where userid=? "; try { pst=conn.prepareStatement(sql); pst.setString(1, user.getUsername()); pst.setString(2, user.getUserpassword()); pst.setString(3, user.getUsernickname()); pst.setBinaryStream(4,file,length); pst.setString(5, user.getUserdescription()); pst.setInt(6, user.getMabeyuse()); pst.setDate(7, user.getUserdate()); pst.setString(8, user.getUsersex()); pst.setString(9, user.getUseraddr()); pst.setString(10, user.getUsermail()); pst.setString(11, user.getUsertel()); pst.setString(12, user.getUseralipayid()); pst.setInt(13, user.getJurisdiction()); pst.setInt(14, user.getUserid()); flag=pst.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { DBUtils.closeAll(conn, pst, res); } return !flag; }
将file标签上传内容存入数据库到这就完成了。
下面要做的是从数据库读取blob数据,并显示到jsp界面:
我的jsp显示界面如下:
<table class="tablelist"> <thead> <tr> <th><input id="allSelect" type="checkbox" value="" /></th> <th>用户编号</th> <th>用户名</th> <th>密码</th> <th>昵称</th> <th>头像</th> <th>个人描述</th> <th>maybe</th> <th>用户生日</th> <th>用户性别</th> <th>收货地址</th> <th>邮箱</th> <th>手机号</th> <th>支付宝账号</th> <th>权限</th> </tr> </thead> <tbody> <c:forEach items="${userpage.data }" var="user"> <tr> <td><input name="isSelect" id="${user.userid}" type="checkbox" onchange="selUser(${user.userid})"/></td> <td>${user.userid}</td> <td>${user.username}</td> <td>${user.userpassword}</td> <td>${user.usernickname}</td> <td><img alt="" width="100px" height="75px" src="/xxx/upload/${user.userdescription}.jpg"> </td> <td>${user.userdescription}</td> <td>${user.mabeyuse}</td> <td>${user.userdate}</td> <td>${user.usersex}</td> <td>${user.useraddr}</td> <td>${user.usermail}</td> <td>${user.usertel}</td> <td>${user.useralipayid}</td> <td>${user.jurisdiction}</td> </tr> </c:forEach> </tbody> </table>
图片用img标签显示 用src读取服务器上图片路径:
我从数据库用getBlob()方法获取blob类型数据,然后新建User对象进行封装这里就不讲了。
后台将blob数据转化为图片的代码如下:
@WebServlet("/UserServlet") public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/*"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String scurrentpage=request.getParameter("currentpage"); if(scurrentpage==null){ scurrentpage="1"; } UserDao userDao=new UserDaoImpl(); UserPage uPage= userDao.findUserByPage(Integer.parseInt(scurrentpage), 5); List<User> list=uPage.getData(); //这里是获取分页查询到的User对象的List 下面遍历每个User for (User us : list) { if (us.getUserpicture()==null||us.getUserpicture().equals("")) { continue; }else{ try { InputStream is=us.getUserpicture().getBinaryStream(); //获取Blob类型变量 并转化为二进制输入流 if(is!=null){ String uuid=UUID.randomUUID().toString(); //给图片取个独一无二的名字 is = new BufferedInputStream(is) ; //将输入流读入缓冲区 BufferedImage bi = ImageIO.read(is) ; //利用ImageIo对象转化为Image对象 OutputStream oi=new FileOutputStream("D:/tomcat8/webapps/xxx/upload/"+uuid+".jpg");//新建输出流 保存文件到服务器指定路径 ImageIO.write(bi, "jpeg", oi); //写入文件 oi.close(); is.close(); us.setUserdescription(uuid);//我将图片名字存入User对象中,方便jsp界面读取 } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } request.setAttribute("userpage", uPage); request.getRequestDispatcher("/user.jsp").forward(request, response); } }//在jsp页面读取和读取服务器图片相同//至此向数据库存入图片,以及从数据库读取图片显示到jsp界面 均已完成。
时间: 2024-10-14 01:02:14