您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“Javaweb怎么實現(xiàn)頭像上傳及讀取顯示”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“Javaweb怎么實現(xiàn)頭像上傳及讀取顯示”吧!
思路:
1.如果要上傳頭像并要顯示的話,可以創(chuàng)建一個工具類來將獲取的頭像另外復(fù)制一份放在工程目錄下,并修改其文件名(防止名字相同有沖突)。
2.要創(chuàng)建表,另一個img表用于存放該學(xué)生的頭像的存儲路徑、頭像名稱、以及該學(xué)生對應(yīng)的ID。
3.在html頁面中可通過設(shè)置表單在獲取信息,注意的是由于表單的enctype屬性要設(shè)為"multipart/form-data",設(shè)置為該屬性可以上傳文件。
4.創(chuàng)建servlet來對數(shù)據(jù)進行封裝,進行將數(shù)據(jù)添加數(shù)據(jù)庫中,并將信息發(fā)送給頁面
步驟:1.先將兩個表給創(chuàng)建出來。這里我使用mysql進行創(chuàng)建,注意的是user的學(xué)號要和Img的學(xué)號用外鍵關(guān)聯(lián)。
創(chuàng)建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.創(chuàng)建完數(shù)據(jù)庫后,先將前臺的html設(shè)計好,設(shè)置表單來獲取用戶填寫的信息。
<!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="發(fā)布"> </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.創(chuàng)建一個工具類Fileupload.java,用于獲取并處理表單中的數(shù)據(jù)。
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.創(chuàng)建DiskFileItemFactory對象,設(shè)置緩沖區(qū)大小和臨時目錄文件 DiskFileItemFactory factory = new DiskFileItemFactory(); //2.創(chuàng)建ServletFileUpload對象,并設(shè)置上傳文件的大小限制 ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(10 * 1024 * 1024);//以byte為單位 1024byte->1KB*1024=1M->1M*10=10M sfu.setHeaderEncoding("utf-8"); //3.調(diào)用ServletFileUpload.parseRequest方法來解析對象,得到一個保存了所有上傳內(nèi)容的List對象 List<FileItem> fileItemList = sfu.parseRequest(request); Iterator<FileItem> fileItems = fileItemList.iterator(); //創(chuàng)建一個Map集合,用于添加表單元素 Map<String, String> map = new TreeMap<String, String>(); //4.遍歷fileItems,每迭代一個對象,調(diào)用其isFormField方法判斷是否是上傳文件 while ((fileItems.hasNext())) { FileItem fileItem = fileItems.next(); try{ //普通的表單元素 if (fileItem.isFormField()) { String name = fileItem.getFieldName();//name的屬性值 String value = fileItem.getString("utf-8");//name對應(yīng)的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 //將文件名存入到數(shù)組中 map.put("fileName", fileName); map.put("newFileName", newFileName); // 5. 調(diào)用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下默認(rèn)的頭像,如果不是才執(zhí)行刪除 if(!fileName.contains("empty")|| !newFileName.contains("empty")){ // 6. 調(diào)用FileItem的delete()方法,刪除臨時文件 fileItem.delete(); } } } }catch (StringIndexOutOfBoundsException e ){ //若為空指指針 //未上傳圖片則按原來的圖片顯示 //設(shè)置為false,在進行數(shù)據(jù)庫操作時不對圖片進行操作 System.out.println("出現(xiàn)異常"); 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.創(chuàng)建對應(yīng)的servlet來處理用戶添加的信息以及將數(shù)據(jù)分別存入到數(shù)據(jù)庫中
注意:在這里添加信息到數(shù)據(jù)庫中的操作和創(chuàng)建user對象是我在創(chuàng)建一個方法來實現(xiàn),到時可根據(jù)自己的方法來實現(xiàn)方法
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); //創(chuàng)建img對象用來封裝數(shù)據(jù) Img img = new Img(); try { BeanUtils.populate(img,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } System.out.println("servlet獲取的img數(shù)據(jù)為:"+img); //創(chuàng)建service對象將頭像數(shù)據(jù)存入到表中 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>
實現(xiàn)后效果如下
此時打開數(shù)據(jù)庫便發(fā)現(xiàn)添加了該圖片對應(yīng)的數(shù)據(jù)
如何根據(jù)對應(yīng)的id來獲取圖片的路徑并顯示出來
到此,相信大家對“Javaweb怎么實現(xiàn)頭像上傳及讀取顯示”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。