Java?web實現(xiàn)頭像上傳以及讀取顯示
最近在做一個學生的信息管理系統(tǒng),其中就有一個功能是要上傳頭像以及實現(xiàn)顯示的功能,那么要如何實現(xiàn)呢?
思路:
1.如果要上傳頭像并要顯示的話,可以創(chuàng)建一個工具類來將獲取的頭像另外復制一份放在工程目錄下,并修改其文件名(防止名字相同有沖突)。
2.要創(chuàng)建表,另一個img表用于存放該學生的頭像的存儲路徑、頭像名稱、以及該學生對應的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的學號要和Img的學號用外鍵關(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對應的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下默認的頭像,如果不是才執(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)建對應的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>
? ? <h3>圖片</h3>
? ? <img width="150" height="150" id="imgid">
</body>
</html>實現(xiàn)后效果如下


此時打開數(shù)據(jù)庫便發(fā)現(xiàn)添加了該圖片對應的數(shù)據(jù)

如何根據(jù)對應的id來獲取圖片的路徑并顯示出來

基本效果就這樣子
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java多線程中ReentrantLock與Condition詳解
這篇文章主要介紹了Java多線程中ReentrantLock與Condition詳解,需要的朋友可以參考下2017-11-11
@DynamicUpdate //自動更新updatetime的問題
這篇文章主要介紹了@DynamicUpdate //自動更新updatetime的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
Spring Data JPA實現(xiàn)排序與分頁查詢超詳細流程講解
在介紹Spring Data JPA的時候,我們首先認識下Hibernate。Hibernate是數(shù)據(jù)訪問解決技術(shù)的絕對霸主,使用O/R映射技術(shù)實現(xiàn)數(shù)據(jù)訪問,O/R映射即將領(lǐng)域模型類和數(shù)據(jù)庫的表進行映射,通過程序操作對象而實現(xiàn)表數(shù)據(jù)操作的能力,讓數(shù)據(jù)訪問操作無須關(guān)注數(shù)據(jù)庫相關(guān)的技術(shù)2022-10-10
Java 多線程并發(fā)AbstractQueuedSynchronizer詳情
這篇文章主要介紹了Java 多線程并發(fā)AbstractQueuedSynchronizer詳情,文章圍繞主題展開想象的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下2022-06-06
springcloud client指定注冊到eureka的ip與端口號方式
這篇文章主要介紹了springcloud client指定注冊到eureka的ip與端口號方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
Java線程池隊列PriorityBlockingQueue原理分析
這篇文章主要介紹了Java線程池隊列PriorityBlockingQueue原理分析,PriorityBlockingQueue隊列是?JDK1.5?的時候出來的一個阻塞隊列,但是該隊列入隊的時候是不會阻塞的,永遠會加到隊尾,需要的朋友可以參考下2023-12-12
Java與Oracle實現(xiàn)事務(JDBC事務)實例詳解
這篇文章主要介紹了Java與Oracle實現(xiàn)事務(JDBC事務)實例詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05

