您好,登錄后才能下訂單哦!
本篇內容主要講解“Javaweb怎么實現頭像上傳及讀取顯示”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Javaweb怎么實現頭像上傳及讀取顯示”吧!
思路:
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> <h4>圖片</h4> <img width="150" height="150" id="imgid"> </body> </html>
實現后效果如下
此時打開數據庫便發現添加了該圖片對應的數據
如何根據對應的id來獲取圖片的路徑并顯示出來
到此,相信大家對“Javaweb怎么實現頭像上傳及讀取顯示”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。