1、在jsp頁面添加上傳,點擊按鈕,點擊觸發上傳圖片事件
<input class="image_bg" type="file" style="display: none;" id="file" accept="image/*" />
2、在引用的js里面添加方法,這里需要首先引入jquery
//允許上傳的圖片類型 var allowTypes = [ 'image/jpg', 'image/jpeg', 'image/png' ]; // 500kb var maxSize = 1024 * 1024; // 圖片最大寬度 var maxWidth = 1920; // 圖片最大高度 var maxHeight = 1080; // 最大上傳圖片數量,限制兩張 var maxCount = 1; $(".image_bg").on('change', function(event) { readFile(event); }); function readFile(event) { var files = event.target.files; // 如果沒有選中文件,直接返回 if (files.length === 0) { return; } var file = files[files.length - 1]; var reader = new FileReader(); // 如果類型不在允許的類型范圍內 if (allowTypes.indexOf(file.type) === -1) { AlertDialog('該類型不允許上傳'); return; } console.log('size===' + file.size) console.log('filewidth==' + file.width) console.log('fileheight==' + file.height) if (file.size > maxSize) { AlertDialog("圖片超過" + (maxSize / 1024) + "KB,不允許上傳!"); return; } reader.onload = function(e) { var img = new Image(); img.onload = function() { console.log('width==' + img.width) console.log('height==' + img.height) var w = img.width; var h = img.height; var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); // 設置 canvas 的寬度和高度 canvas.width = w; canvas.height = h; ctx.drawImage(img, 0, 0, w, h); var imgbase64 = canvas.toDataURL('image/jpeg'); // console.log(imgbase64); /** 將上傳的圖片轉碼到頁面區域 */ var start = imgbase64.indexOf('base64,') + 7; imgbase64 = imgbase64.substring(start, imgbase64.length); imgbase64 = imgbase64.replace(/\+/g, "%2B"); $.ajax({ contentType : "application/x-www-form-urlencoded; charset=utf-8", type : "post", url : htmlVal.htmlUrl + "?uploadimage=", data : { image : imgbase64 }, success : function(result) { if (result == "ok") { location.href = location.href; } if (result == "images_up_to_limit") { AlertDialog("該類型圖片到達上限"); } if (result == "10002") { AlertDialog("參數錯誤!"); } } }) img = null; }; img.src = e.target.result; }; reader.readAsDataURL(file); } /** * 刪除圖片 */ function deleteImage() { ConfirmDialog("確定刪除嗎?", function() { $.ajax({ contentType : "application/x-www-form-urlencoded; charset=utf-8", type : "post", url : htmlVal.htmlUrl + "?deleteimage=", success : function(result) { if (result == "error") { AlertDialog("刪除失敗"); } if (result == "ok") { location.href = location.href; } } }) }, function() { }) }
3、后台處理上傳的圖片base64編碼,將編碼轉成圖片
/** * 上傳圖片 * @return */ @HandlesEvent("uploadimage") public Resolution doUploadImage() { System.out.println("SaleSetting.doUploadImage()"); logRequest(); // if (school.getIndexImage() != null && !school.getIndexImage().trim().equals("")){ // return getStringResolution("images_up_to_limit"); // } String imageBase = getParam("image", ""); int userId = getCurrentUserId(); String imageType = "SchoolIndexImage"; String imagePath = saveImage(imageBase, userId, imageType); school.setIndexImage(imagePath); cmService.updateSchool(school); return getStringResolution("ok"); } /** * 保存圖片,根據圖片的類型存儲圖片路徑 * @param imageBase * @param userId * @param imageType * @return 返回上傳圖片的路徑 */ private String saveImage(String imageBase, int userId, String imageType) { String data = ""; try{ data = URLDecoder.decode(imageBase, "UTF-8"); } catch (UnsupportedEncodingException e){ e.printStackTrace(); } if (data == null || data.contentEquals("")){ return ""; } int now = Utils.currentSeconds(); String filePath = "sale/" + userId + "/" + imageType; String dir = Constants.PATH_FILE + filePath; Utils.makeSureDirExists(dir); String path = dir + "/" + now + ".jpg"; Utils.generateImageFromBase64(data, path); return filePath + "/" + now + ".jpg"; }
Utils.java 工具類
package util; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.Serializable; import sun.misc.BASE64Decoder; /** * @author dayu * @version 創建時間:2018年5月8日 上午9:55:16 類說明 */ public class Utils implements Serializable { private static final long serialVersionUID = -5714133117682920152L; public static int currentSeconds() { return (int)(System.currentTimeMillis() / 1000L); } public static File makeSureDirExists(String dirPath) { File dir = new File(dirPath); if (!dir.exists()) { dir.mkdirs(); } return dir; } // base64字符串轉化成圖片 public static boolean generateImageFromBase64(String imgStr, String path) { // 對字節數組字符串進行Base64解碼並生成圖片 if (imgStr == null) // 圖像數據為空 return false; BASE64Decoder decoder = new BASE64Decoder(); try{ // Base64解碼 byte[] b = decoder.decodeBuffer(imgStr); for (int i = 0; i < b.length; ++i){ if (b[i] < 0){// 調整異常數據 b[i] += 256; } } // 生成jpeg圖片 // String imgFilePath = "d://222.jpg";//新生成的圖片 OutputStream out = new FileOutputStream(path); out.write(b); out.flush(); out.close(); return true; } catch (Exception e){ return false; } } }