最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java?web實(shí)現(xiàn)頭像上傳以及讀取顯示

 更新時(shí)間:2022年06月23日 17:12:16   作者:鹿谷門実  
這篇文章主要為大家詳細(xì)介紹了Java?web實(shí)現(xiàn)頭像上傳以及讀取顯示,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

最近在做一個(gè)學(xué)生的信息管理系統(tǒng),其中就有一個(gè)功能是要上傳頭像以及實(shí)現(xiàn)顯示的功能,那么要如何實(shí)現(xiàn)呢?

思路:

1.如果要上傳頭像并要顯示的話,可以創(chuàng)建一個(gè)工具類來將獲取的頭像另外復(fù)制一份放在工程目錄下,并修改其文件名(防止名字相同有沖突)。
2.要?jiǎng)?chuàng)建表,另一個(gè)img表用于存放該學(xué)生的頭像的存儲(chǔ)路徑、頭像名稱、以及該學(xué)生對(duì)應(yīng)的ID。
3.在html頁面中可通過設(shè)置表單在獲取信息,注意的是由于表單的enctype屬性要設(shè)為"multipart/form-data",設(shè)置為該屬性可以上傳文件。
4.創(chuàng)建servlet來對(duì)數(shù)據(jù)進(jìn)行封裝,進(jìn)行將數(shù)據(jù)添加數(shù)據(jù)庫中,并將信息發(fā)送給頁面

步驟:1.先將兩個(gè)表給創(chuàng)建出來。這里我使用mysql進(jìn)行創(chuàng)建,注意的是user的學(xué)號(hào)要和Img的學(xué)號(hào)用外鍵關(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ù)庫后,先將前臺(tái)的html設(shè)計(jì)好,設(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)建一個(gè)工具類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對(duì)象,設(shè)置緩沖區(qū)大小和臨時(shí)目錄文件
? ? ? ? ? ? ? ? DiskFileItemFactory factory = new DiskFileItemFactory();
? ? ? ? ? ? ? ? //2.創(chuàng)建ServletFileUpload對(duì)象,并設(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方法來解析對(duì)象,得到一個(gè)保存了所有上傳內(nèi)容的List對(duì)象
? ? ? ? ? ? ? ? List<FileItem> fileItemList = sfu.parseRequest(request);
? ? ? ? ? ? ? ? Iterator<FileItem> fileItems = fileItemList.iterator();

? ? ? ? ? ? ? ? //創(chuàng)建一個(gè)Map集合,用于添加表單元素
? ? ? ? ? ? ? ? Map<String, String> map = new TreeMap<String, String>();

? ? ? ? ? ? ? ? //4.遍歷fileItems,每迭代一個(gè)對(duì)象,調(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對(duì)應(yīng)的value值
? ? ? ? ? ? ? ? ? ? ? ? ? ? //添加進(jìn)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("擴(kuò)展名:" + 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()方法,刪除臨時(shí)文件
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? fileItem.delete();
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }catch (StringIndexOutOfBoundsException e ){
? ? ? ? ? ? ? ? ? ? ? ? //若為空指指針
? ? ? ? ? ? ? ? ? ? ? ? //未上傳圖片則按原來的圖片顯示
? ? ? ? ? ? ? ? ? ? ? ? //設(shè)置為false,在進(jìn)行數(shù)據(jù)庫操作時(shí)不對(duì)圖片進(jìn)行操作
? ? ? ? ? ? ? ? ? ? ? ? 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)建對(duì)應(yīng)的servlet來處理用戶添加的信息以及將數(shù)據(jù)分別存入到數(shù)據(jù)庫中

注意:在這里添加信息到數(shù)據(jù)庫中的操作和創(chuàng)建user對(duì)象是我在創(chuàng)建一個(gè)方法來實(shí)現(xiàn),到時(shí)可根據(jù)自己的方法來實(shí)現(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對(duì)象用來封裝數(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對(duì)象將頭像數(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>

實(shí)現(xiàn)后效果如下

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

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

基本效果就這樣子

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java多線程中ReentrantLock與Condition詳解

    Java多線程中ReentrantLock與Condition詳解

    這篇文章主要介紹了Java多線程中ReentrantLock與Condition詳解,需要的朋友可以參考下
    2017-11-11
  • 講解Java中的基礎(chǔ)類庫和語言包的使用

    講解Java中的基礎(chǔ)類庫和語言包的使用

    這篇文章主要介紹了Java中的基礎(chǔ)類庫和語言包的使用,是Java入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-09-09
  • 基于@Table注解無法使用及報(bào)紅的解決

    基于@Table注解無法使用及報(bào)紅的解決

    這篇文章主要介紹了基于@Table注解無法使用及報(bào)紅的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • hibernate測試時(shí)遇到的幾個(gè)異常及解決方法匯總

    hibernate測試時(shí)遇到的幾個(gè)異常及解決方法匯總

    今天小編就為大家分享一篇關(guān)于hibernate測試時(shí)遇到的幾個(gè)異常及解決方法匯總,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • @DynamicUpdate //自動(dòng)更新updatetime的問題

    @DynamicUpdate //自動(dòng)更新updatetime的問題

    這篇文章主要介紹了@DynamicUpdate //自動(dòng)更新updatetime的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Spring Data JPA實(shí)現(xiàn)排序與分頁查詢超詳細(xì)流程講解

    Spring Data JPA實(shí)現(xiàn)排序與分頁查詢超詳細(xì)流程講解

    在介紹Spring Data JPA的時(shí)候,我們首先認(rèn)識(shí)下Hibernate。Hibernate是數(shù)據(jù)訪問解決技術(shù)的絕對(duì)霸主,使用O/R映射技術(shù)實(shí)現(xiàn)數(shù)據(jù)訪問,O/R映射即將領(lǐng)域模型類和數(shù)據(jù)庫的表進(jìn)行映射,通過程序操作對(duì)象而實(shí)現(xiàn)表數(shù)據(jù)操作的能力,讓數(shù)據(jù)訪問操作無須關(guān)注數(shù)據(jù)庫相關(guān)的技術(shù)
    2022-10-10
  • Java 多線程并發(fā)AbstractQueuedSynchronizer詳情

    Java 多線程并發(fā)AbstractQueuedSynchronizer詳情

    這篇文章主要介紹了Java 多線程并發(fā)AbstractQueuedSynchronizer詳情,文章圍繞主題展開想象的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的小伙伴可以參考一下
    2022-06-06
  • springcloud client指定注冊到eureka的ip與端口號(hào)方式

    springcloud client指定注冊到eureka的ip與端口號(hào)方式

    這篇文章主要介紹了springcloud client指定注冊到eureka的ip與端口號(hào)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Java線程池隊(duì)列PriorityBlockingQueue原理分析

    Java線程池隊(duì)列PriorityBlockingQueue原理分析

    這篇文章主要介紹了Java線程池隊(duì)列PriorityBlockingQueue原理分析,PriorityBlockingQueue隊(duì)列是?JDK1.5?的時(shí)候出來的一個(gè)阻塞隊(duì)列,但是該隊(duì)列入隊(duì)的時(shí)候是不會(huì)阻塞的,永遠(yuǎn)會(huì)加到隊(duì)尾,需要的朋友可以參考下
    2023-12-12
  • Java與Oracle實(shí)現(xiàn)事務(wù)(JDBC事務(wù))實(shí)例詳解

    Java與Oracle實(shí)現(xiàn)事務(wù)(JDBC事務(wù))實(shí)例詳解

    這篇文章主要介紹了Java與Oracle實(shí)現(xiàn)事務(wù)(JDBC事務(wù))實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-05-05

最新評(píng)論

招远市| 石首市| 凤山县| 云梦县| 锡林郭勒盟| 武穴市| 大方县| 重庆市| 中阳县| 禄丰县| 潼南县| 平谷区| 河曲县| 武城县| 绵阳市| 东方市| 青川县| 夏邑县| 德化县| 长泰县| 南安市| 庐江县| 江源县| 怀柔区| 平乐县| 许昌县| 进贤县| 阜阳市| 忻州市| 前郭尔| 安化县| 启东市| 元朗区| 绵竹市| 合肥市| 台东县| 常德市| 陈巴尔虎旗| 开化县| 嘉荫县| 册亨县|