用ajax來實現新增圖片
阿新 • • 發佈:2018-12-07
大家可能在日常工作中經常遇到這種操作,例如:你要去給用於新增資訊的時候經常去給使用者新增頭像。這時候不只是新增頭像那麼簡單,你給使用者選擇照片的時候還需要將選擇好的照片給回顯出來,這個時候,就需要用到我們這個ajax提交照片與資料庫進行後臺互動的時候了。
我們想要與資料庫進行後臺互動,肯定少不了要用到我們的ajax,那麼普通的ajax是無法實現這種效果的,我們需要用到Jquery-form.js(可以去官網進行下載:下載的時候不會直接下載,你可以把文字上的內容複製到自己寫的js上面 點選開啟連結)。
前臺:(這裡用到了前臺與後臺的資料庫互動,所以我們需要用到了success從後臺獲取資料,從百度上收不到,這是自己的實戰經驗,我在後臺發現好像只能用hashmap的返回值,如有其它的,希望大家通過評論區告訴我一下)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-1.8.2.js"></script> <script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-form.min.js"></script> <style> /**按鈕樣式**/ .file { position: relative; display: inline-block; background: #D0EEFF; border: 1px solid #99D3F5; border-radius: 4px; padding: 4px 12px; overflow: hidden; color: #1E88C7; text-decoration: none; text-indent: 0; line-height: 20px; } .file input { position: absolute; font-size: 100px; right: 0; top: 0; opacity: 0; } .file:hover { background: #AADFFD; border-color: #78C3F3; color: #004974; text-decoration: none; } </style> <script type="text/javascript"> function isPictrue(target){ var fileSize = 0; var filetypes = [ ".GIF", ".gif", ".JPEG",".jpeg",".JPG",".jpg", ".PNG", ".png", ]; var filepath = target.value; if (filepath) { var isnext = false; var fileend = filepath.substring(filepath.lastIndexOf(".")); for (var i = 0; i < filetypes.length; i++) { if (filetypes[i] == fileend) { isnext = true; break; } } if (!isnext) { alert("不接受此檔案型別!"); target.value = ""; return ; } } else { alert("請選擇圖片!"); return ; } } function toHuiXian(target){ isPictrue(target); var b={ url:"<%=request.getContextPath() %>/thing/toHuiXian.action", type:"post", dataType:"json", success:function(mes){ showResponse(mes); } }; $("#headImgform").ajaxSubmit(b); } function showResponse(mes){ $("#im").attr("src","<%=request.getContextPath() %>/"+mes.address); } </script> </head> <body> <img alt="" width="100px" height="50px" id="im" src=""><p></p>選擇圖片: <form action="" id="headImgform" method="post" enctype="multipart/form-data"> <a href="javascript:;" class="file" style="visibility:true">選擇檔案 <input name="multFile" type="file" onchange="toHuiXian(this)"> </a> </form> </body> </html>
後臺程式碼
@RequestMapping("toHuiXian") @ResponseBody public HashMap<String,Object> toHuiXian(MultipartFile multFile,HttpServletRequest req){ String upFile = Upload.upFile(multFile, req); System.out.println(upFile); String b=upFile.substring(upFile.indexOf("image")); System.out.println(b); HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("address", b); return hashMap; }
Upload的工具類:
public static String upFile(MultipartFile file, HttpServletRequest req) {
// 獲取檔名
String fileName = file.getOriginalFilename();
// 獲取檔案的字尾名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//自定義 生成隨機檔名
fileName = UUID.randomUUID() + suffixName;
//獲取專案全路徑
String realPath = req.getServletContext().getRealPath("/");
System.out.println(realPath);
//建立日期資料夾路徑
String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
//檔案全路徑
String fileAllPath = "image" +File.separator + datePath +File.separator + fileName;
//上傳檔案全路徑
File dest = new File(realPath + File.separator + fileAllPath);
// 檢測是否存在目錄 沒有則建立
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (Exception e) {
e.printStackTrace();
return "fial";
}
return fileAllPath;
}
這裡有一個細節:因為我們做的是使用者的頭像回顯,而不是放在資料中,所以不需要持久化,我們把它放在eclipse中Tomcat自動開啟的空間,當我們重新部署的時候就會自動清除,簡單,快捷。