我的圖片上傳使用form表單,html: css js 後臺把數據傳給資料庫,成功後跳轉頁面,在html頁面中用這個<img src="${sessionScope.imgurl}"/> ...
我的圖片上傳使用form表單,html:
<form action="imagsUp" enctype="multipart/form-data" method="post" >
<img src="img/img_basic.jpg"id="img" style="width:120px;height:110px;float:left;"/> <a id="img_a"> 選擇你的新頭像--〉</a> <input id="file" name="img_file" onchange="c()" type="file" style="display:none;"><br> <div id="imgcss"class="imgcss"style="float:left;margin-top:-20px;"><i class="icon-plus" id="i"></i></div> <button id="Up" type="submit" value="確定" class="button"style="">確定</button>〈/form>
css
.imgcss{ width:100px;height:100px;border:1px solid #f0f0f0; } .imgcss:hover i{ color:#CCCCFF; background-color:#f0f0f0; } .imgcss i{ font-size:100px;width-size:2px;color:#f0f0f0; } /*圖片*/ #img_a{ float:left;margin-top:40px;font-weight:bold;color:#C0C0C0; } #Up{ float:right; height:20px;width:60px;font-size:15px;margin-top:20px; }
js
//這個方法是隱藏的文件上傳控制項點擊方
function c () { var r= new FileReader(); var f=$("#file")[0].files[0]; r.readAsDataURL(f); r.onload=function (e) { $("#i").css('display','none'); $("#imgcss").css("background-image","url("+this.result+")"); $("#imgcss").removeClass("imgcss"); $("#imgcss").css({"background-size":"cover","width":"100px","height":"100px"}); }; } $(document).ready(function() { $("#imgcss").click(function(){ $("#file").click(); });});
FileItemFactory factory = new DiskFileItemFactory(); // 創建文件上傳處理器 ServletFileUpload upload = new ServletFileUpload(factory); // 開始解析請求信息 List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } // 對所有請求信息進行判斷 Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // 信息為普通的格式 if (item.isFormField()) { String fieldName = item.getFieldName(); String value = item.getString(); request.setAttribute(fieldName, value); } // 信息為文件格式 else { String fileName = item.getName(); String suffix = fileName.substring(fileName.lastIndexOf('.')); //圖片名 System.out.println("圖片名字"+fileName); //尾碼名 System.out.println(suffix); int index = fileName.lastIndexOf("\\"); fileName = fileName.substring(index + 1); request.setAttribute("realFileName", fileName); //圖片url String basePath = getServletConfig().getServletContext().getRealPath("/")+"img"; System.out.println(basePath); //新文件名 String newFileName = new Date().getTime() + suffix; System.out.println(newFileName); File file = new File(basePath, newFileName); try { item.write(file); int userId = (Integer) request.getSession().getAttribute("id"); System.out.println("userId:" + userId); //存圖片信息 imagsTT.ImagsUp(userId, newFileName,basePath); session.setAttribute("imgurl", "img/" + newFileName); System.out.print("用圖片返回查詢的數據"+"img/" + newFileName); } catch (Exception e) { e.printStackTrace(); } } request.setAttribute("msg","文件上傳成功!"); getServletContext().getRequestDispatcher("/My.jsp").forward(request, response); return; }
後臺把數據傳給資料庫,成功後跳轉頁面,在html頁面中用這個<img src="${sessionScope.imgurl}"/>