最近在做一个学生的信息管理系统,其中就有一个功能是要上传头像以及实现显示的功能,那么要如何实现呢?
思路:
1.如果要上传头像并要显示的话,可以创建一个工具类来将获取的头像另外复制一份放在工程目录下,并修改其文件名(防止名字相同有冲突)。
2.要创建表,另一个img表用于存放该学生的头像的存储路径、头像名称、以及该学生对应的ID。
3.在html页面中可通过设置表单在获取信息,注意的是由于表单的enctype属性要设为"multipart/form-data",设置为该属性可以上传文件。
4.创建servlet来对数据进行封装,进行将数据添加数据库中,并将信息发送给页面
步骤:1.先将两个表给创建出来。这里我使用mysql进行创建,注意的是user的学号要和Img的学号用外键关联。
创建Img表
CREATE TABLE `img` ( `id` int(4) NOT NULL AUTO_INCREMENT, `image_path` varchar(255) DEFAULT NULL, `old_name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8
2.创建完数据库后,先将前台的html设计好,设置表单来获取用户填写的信息。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) --> <script src="js/jquery-2.1.0.min.js"></script> </head> <body> <form action="addimgServlet" method="post" accept-charset="utf-8" enctype="multipart/form-data"> <div > <img src="" width="150" height="150" id="previewimg"> </div> <div > <input type="file" id="img" name="img" onChange="preview(this)"/> <span class="add">+</span> </div> <input type="submit" id="submit_content" value="发布"> </form> </body> <script type="text/javascript"> function preview(obj){ var img = document.getElementById("previewimg"); img.src = window.URL.createObjectURL(obj.files[0]); } </script> </html>
3.创建一个工具类Fileupload.java,用于获取并处理表单中的数据。
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; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.util.*; public class FileUpload { private static final long serialVersionUID = 1L; public Map<String,String> File_upload(HttpServletRequest request,String filepath) { //判断上传的表单是否为multipart/form-data类型 if (ServletFileUpload.isMultipartContent(request)) { try { //1.创建DiskFileItemFactory对象,设置缓冲区大小和临时目录文件 DiskFileItemFactory factory = new DiskFileItemFactory(); //2.创建ServletFileUpload对象,并设置上传文件的大小限制 ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(10 * 1024 * 1024);//以byte为单位 1024byte->1KB*1024=1M->1M*10=10M sfu.setHeaderEncoding("utf-8"); //3.调用ServletFileUpload.parseRequest方法来解析对象,得到一个保存了所有上传内容的List对象 List<FileItem> fileItemList = sfu.parseRequest(request); Iterator<FileItem> fileItems = fileItemList.iterator(); //创建一个Map集合,用于添加表单元素 Map<String, String> map = new TreeMap<String, String>(); //4.遍历fileItems,每迭代一个对象,调用其isFormField方法判断是否是上传文件 while ((fileItems.hasNext())) { FileItem fileItem = fileItems.next(); try{ //普通的表单元素 if (fileItem.isFormField()) { String name = fileItem.getFieldName();//name的属性值 String value = fileItem.getString("utf-8");//name对应的value值 //添加进Map集合中 map.put(name, value); } else {//否则即为<input type="file">上传的文件 if(fileItem.getName()==null||fileItem.getFieldName()==null){ map.put("fileName","empty"); map.put("newFileName","empty"); }else { String fileName = fileItem.getName();// 文件名称 System.out.println("原文件名:" + fileName);// Koala.jpg String suffix = fileName.substring(fileName.lastIndexOf('.')); System.out.println("扩展名:" + suffix);// .jpg // 新文件名(唯一) String newFileName = new Date().getTime() + suffix; System.out.println("新文件名:" + newFileName);// image\1478509873038.jpg //将文件名存入到数组中 map.put("fileName", fileName); map.put("newFileName", newFileName); // 5. 调用FileItem的write()方法,写入文件 String context = filepath+newFileName ; System.out.println("图片的路径为"+context); File file = new File(context); System.out.println(file.getAbsolutePath()); fileItem.write(file); //判断该文件是否为head_img下默认的头像,如果不是才执行删除 if(!fileName.contains("empty")|| !newFileName.contains("empty")){ // 6. 调用FileItem的delete()方法,删除临时文件 fileItem.delete(); } } } }catch (StringIndexOutOfBoundsException e ){ //若为空指指针 //未上传图片则按原来的图片显示 //设置为false,在进行数据库操作时不对图片进行操作 System.out.println("出现异常"); map.put("fileName","empty"); map.put("newFileName","empty"); e.printStackTrace(); } } return map; } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } return null; } }
4.创建对应的servlet来处理用户添加的信息以及将数据分别存入到数据库中
注意:在这里添加信息到数据库中的操作和创建user对象是我在创建一个方法来实现,到时可根据自己的方法来实现方法
package domain; public class Img { private String fileName; private String newFileName; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getNewFileName() { return newFileName; } public void setNewFileName(String newFileName) { this.newFileName = newFileName; } @Override public String toString() { return "Img{" + "fileName='" + fileName + '\'' + ", newFileName='" + newFileName + '\'' + '}'; } }
package servlet; import dao.UserDaoImpl; import domain.Img; import org.apache.commons.beanutils.BeanUtils; import util.FileUpload; 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 java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/addimgServlet") public class addimgServlet extends HttpServlet { //为类可持久化 private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //通过工具类获取成员的信息 String file = getServletContext().getRealPath("/head_img/"); Map<String,String> map = new FileUpload().File_upload(request,file); //创建img对象用来封装数据 Img img = new Img(); try { BeanUtils.populate(img,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } System.out.println("servlet获取的img数据为:"+img); //创建service对象将头像数据存入到表中 UserDaoImpl userDao = new UserDaoImpl(); userDao.addimg(img); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
==========================
package servlet; import com.fasterxml.jackson.databind.ObjectMapper; import dao.UserDaoImpl; import domain.Head_img; 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 java.io.IOException; @WebServlet("/getimgServlet") public class getimgServlet extends HttpServlet { //为类可持久化 private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserDaoImpl userDao = new UserDaoImpl(); Head_img img = userDao.getimg(Integer.parseInt(request.getParameter("id"))); System.out.println("获取的图象的路径为:"+img); ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json;charset=utf-8"); mapper.writeValue(response.getOutputStream(),img); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
5.最后,在userlList.html中接收信息并显示出来
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>显示图片</title> <script src="js/jquery-2.1.0.min.js"></script> <script> function GetRequest() { var url = location.search; //获取url中"?"符后的字串 var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for ( var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return theRequest; } $(function () { $.get("getimgServlet",{id:GetRequest()["id"]},function (data) { $("#imgid").attr("src",data.image_path); }) }) </script> </head> <body> <h3>图片</h3> <img width="150" height="150" id="imgid"> </body> </html>
实现后效果如下
基本效果就这样子
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。