SSM+BJUI实现以Base64方式上传照片
生活随笔
收集整理的這篇文章主要介紹了
SSM+BJUI实现以Base64方式上传照片
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
場景
點擊添加--選擇照片--點擊保存--保存到數(shù)據(jù)庫路徑--頁面展示。
實現(xiàn)
前面實現(xiàn)照片上傳可以用其他實現(xiàn),這里是用BJUI來實現(xiàn)。
需要給后臺action傳過去base64Str。
添加頁面代碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%><c:set var="ctx" value="${pageContext.request.contextPath}" /> <script type="text/javascript" src="${ctx}/resources/js/cropper/cropper.js"></script> <link rel="stylesheet" type="text/css" href="${ctx}/resources/js/cropper/cropper.css" /> <script type="text/javascript"src="${ctx}/resources/BJUI/plugins/kindeditor_4.1.10/kindeditor.js"></script> <script type="text/javascript">window.CKEDITOR_BASEPATH = '${ctx}/resources/js/ckeditor/'; </script> <style type="text/css">#user-photo {width:150px;height:150px;margin-top: 10px;margin-left: 115px;}#photo {max-width:100%;max-height:350px;}.img-preview-box {text-align: center;}.img-preview-box > div {display: inline-block;;margin-right: 10px;}.img-preview {overflow: hidden;}.img-preview-box .img-preview-lg {width: 150px;height: 150px;}.img-preview-box .img-preview-md {width: 100px;height: 100px;}.img-preview-box .img-preview-sm {width: 50px;height: 50px;border-radius: 50%;}.modal-backdrop{z-index:0;!important}</style> <script type="text/javascript"src="${ctx}/resources/js/ckeditor/ckeditor.js"></script> <script type="text/javascript">var editor = null;KindEditor.create('textarea[name="content"]',{uploadJson : '${ctx}/bus/pushMessageAction/doSaveImage',fillDescAfterUploadImage : false, //上傳圖片成功后轉(zhuǎn)到屬性頁,為false則直接插入圖片[設(shè)為true方便自定義函數(shù)(X_afterSelect)]items : [ 'source', '|', 'undo', 'redo', '|', 'preview','print', 'template', 'cut', 'copy', 'paste','plainpaste', 'wordpaste', '|', 'justifyleft','justifycenter', 'justifyright', 'justifyfull','insertorderedlist', 'insertunorderedlist', 'indent','outdent', 'subscript', 'superscript', 'clearhtml','quickformat', 'selectall', '|', 'fullscreen', '/','formatblock', 'fontname', 'fontsize', '|','forecolor', 'hilitecolor', 'bold', 'italic','underline', 'strikethrough', 'lineheight','removeformat', '|', 'table', 'hr', 'image' ],//allowFileManager : true,?height : "400px",width :"80%",allowImageUpload : true,autoHeightMode : true,afterCreate : function() {this.loadPlugin('autoheight');},afterBlur : function() {this.sync();} //Kindeditor下獲取文本框信息?}) </script> <div class="bjui-pageContent"><form action="${ctx}/bus/pushMessageAction/doSave"class="ajaxForm" data-toggle="validate" enctype="multipart/form-data"><input type="hidden" name="op" id="j_dialog_op"value="${param.op}${op}"> <input type="hidden" name="id"id="j_dialog_id" value="${message.id}"><inputtype="hidden" name="recordTime" id="recordTime" value="<fmt:formatDate value="${message.recordTime}" pattern="yyyy-MM-dd HH:mm:ss" />"><c:if test="${!empty role}"><input type="hidden" name="status" id="j_dialog_op"value="${message.status}"></c:if><table class="table table-condensed table-hover"><tbody><tr><td colspan="2" align="center" valign="middle"><h4>${title}</h4></td></tr><tr style="height: 30px;"><td><label for="name" class="control-label x90">消息標題:</label><input class="" id="title" type="text" name="title"value="${message.title}" data-rule="標題:required;" /></td></tr><tr style="height: 30px;"><td><label for="name" class="control-label x90">消息類型:</label><select data-toggle="selectpicker" name="messageType"><c:forEach? items= "${codeList}" var="cc"><option value="${cc.codeValue?}" ${message.messageType == cc.codeValue?"selected='selected'":""}>${cc.codeName}</option>????????????????</c:forEach></select></tr><tr style="height: 30px;" id="content_tr"><td colspan="2" align="center"><label for="description" class="float:left;">發(fā)現(xiàn)內(nèi)容:</label><textarea name="content" id="content" class="j-content" rows="4"cols="58" data-toggle="kindeditor" data-minheight="500"style="width: 100%">${message.content}</textarea></td></tr><tr style="height: 30px;" id="vary"><td><label for="name" class="control-label x90">主題圖片:</label><input class="" id="themeImageUrl" type="text"name="themeImageUrl" readonly="readonly"value="${message.themeImageUrl}" /><button? data-target="#changeModal" data-toggle="modal" type="button">選擇文件</button><!-- <input type="file" name="file" id="input"? accept="image/*"? style="width: 40%;"><div id="hidfail"></div> --><!-- <div class="row"><div class="pic"><img src="" id="photo"></div><div class="col-sm-2"><button class="btn btn-primary" onclick="crop()" type="button">裁剪圖片</button><button class="btn btn-primary" onclick="cropfail()" type="button">取消裁剪</button><div><br/><p>結(jié)果:</p><input type="hidden" name="base64Str" id="imgBase64Url"><img src="" alt="裁剪結(jié)果" id="result" ></div></div></div> --> <div class="user-photo-box"> <img id="user-photo" src=""><input type="hidden" name="base64Str" id="imgBase64Url"> </div> </div> <div class="modal fade" id="changeModal" tabindex="1050" role="dialog" aria-hidden="true"> <div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4 class="modal-title text-primary"><i class="fa fa-pencil"></i>裁剪圖片</h4></div><div class="modal-body"><p class="tip-info text-center">未選擇圖片</p><div class="img-container hidden"><img src="" alt="" id="photo"></div><div class="img-preview-box hidden"><hr><span>150*150:</span><div class="img-preview img-preview-lg"></div><!--? <span>100*100:</span><div class="img-preview img-preview-md"></div><span>30*30:</span><div class="img-preview img-preview-sm"></div> --></div></div><div class="modal-footer"><label class="btn btn-danger pull-left" for="photoInput"><input type="file" class="sr-only" id="photoInput" accept="image/*"><span>打開圖片</span></label><button class="btn btn-primary disabled" disabled="true" onclick="sendPhoto()" type="button">提交</button><!--?? <button class="btn btn-close" aria-hidden="true" data-dismiss="modal">取消</button> --></div></div> </div> </div></td></tr><tr style="height: 30px;"><td colspan="2"><label for="description"class="control-label x90">備注:</label> <textarea name="remark"id="remark" rows="5" cols="58">${message.remark}</textarea></td></tr></tbody></table></form> </div><script type="text/javascript">var initCropperInModal = function(img, input, modal){var $image = img;var $inputImage = input;var $modal = modal;var options = {aspectRatio: 1, // 縱橫比viewMode: 2,preview: '.img-preview' // 預覽圖的class名};// 模態(tài)框隱藏后需要保存的數(shù)據(jù)對象var saveData = {};var URL = window.URL || window.webkitURL;var blobURL;$modal.on('show.bs.modal',function () {// 如果打開模態(tài)框時沒有選擇文件就點擊“打開圖片”按鈕if(!$inputImage.val()){$inputImage.click();}}).on('shown.bs.modal', function () {// 重新創(chuàng)建$image.cropper( $.extend(options, {ready: function () {// 當剪切界面就緒后,恢復數(shù)據(jù)if(saveData.canvasData){$image.cropper('setCanvasData', saveData.canvasData);$image.cropper('setCropBoxData', saveData.cropBoxData);}}}));}).on('hidden.bs.modal', function () {// 保存相關(guān)數(shù)據(jù)saveData.cropBoxData = $image.cropper('getCropBoxData');saveData.canvasData = $image.cropper('getCanvasData');// 銷毀并將圖片保存在img標簽$image.cropper('destroy').attr('src',blobURL);});if (URL) {$inputImage.change(function() {var files = this.files;var file;if (!$image.data('cropper')) {return;}if (files && files.length) {file = files[0];if (/^image\/\w+$/.test(file.type)) {if(blobURL) {URL.revokeObjectURL(blobURL);}blobURL = URL.createObjectURL(file);// 重置cropper,將圖像替換$image.cropper('reset').cropper('replace', blobURL);// 選擇文件后,顯示和隱藏相關(guān)內(nèi)容$('.img-container').removeClass('hidden');$('.img-preview-box').removeClass('hidden');$('#changeModal .disabled').removeAttr('disabled').removeClass('disabled');$('#changeModal .tip-info').addClass('hidden');} else {window.alert('請選擇一個圖像文件!');}}});} else {$inputImage.prop('disabled', true).addClass('disabled');}}var sendPhoto = function(){var url=$('#photo').cropper('getCroppedCanvas',{width:300,height:300}).toDataURL('image');$('#user-photo').attr('src',url);$("#imgBase64Url").val(url);console.log("url=="+url);$('#changeModal').modal('hide');};/* var sendPhoto = function(){$('#photo').cropper('getCroppedCanvas',{width:300,height:300}).toBlob(function(blob){// 轉(zhuǎn)化為blob后更改src屬性,隱藏模態(tài)框$('#user-photo').attr('src',URL.createObjectURL(blob));$('#changeModal').modal('hide');});} */$(function(){initCropperInModal($('#photo'),$('#photoInput'),$('#changeModal'));}); </script> <div class="bjui-pageFooter"><ul><li><button type="button" class="btn-close" data-icon="close">關(guān)閉</button></li><li><button type="submit" class="btn-default" data-icon="save">保存</button></li></ul> </div>?
實現(xiàn)效果
點擊上傳照片
裁剪之前
點擊保存后提交到后臺action
@Description("信息保存")@ResponseBody@RequestMapping(value = "/doSave")public Map<String, Object> doSave(TbMessage entity, String op, String base64Str, String[] itemIdStr) {Map<String, Object> jsonResult = null;String msg = "";try {if (base64Str.length()!= 0) {String result = ImageUtil.getInstance().baseUploadImg(Constants.UPLOAD_IMG_MESSAGE, base64Str);entity.setThemeImageUrl((String) result);}String tabid = tabid(ModelAndViewConstants.MESSAGE_SYS_ID);Date now = new Date();ShiroUser currentUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();// 添加if (null == op || ModelAndViewConstants.OPERATION_VALUE_ADD.equals(op)) {entity.setStatus("0");entity.setRecordTime(now);entity.setUserId(currentUser.getUserId());this.service.insert(entity);} else {// 編輯entity.setModifyDate(now);this.service.updateByPrimaryKey(entity);DataSourceHolder.setDataSource("demoDs");//切換云端數(shù)據(jù)源this.service.updateByPrimaryKey(entity);}Integer statusCode = 200;String Msg = "消息信息保存成功";jsonResult = JsonResult.jsonReturn(statusCode, Msg, tabid);return jsonResult;} catch (Exception e) {msg = "接口調(diào)用異常";jsonResult = JsonResult.jsonWsReturn(1, msg, e.getMessage());LogService.getInstance(this).error("保存消息信息失敗" + e.getMessage());String mg = "保存消息信息失敗:" + e.getMessage();jsonResult = JsonResult.jsonReturnErr(mg);return jsonResult;}}前臺控件給后臺action傳過來base64Str。
工具類ImageUtil
public String baseUploadImg(String dir, String base64) {OutputStream out = null;String path = null;String filePath = null;try {if ("".equals(base64)) {return null;}base64 = base64.substring(base64.indexOf(",") + 1);byte[] b = Base64.decode(base64);for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {// 調(diào)整異常數(shù)據(jù)b[i] += 256;}}String fileName = dir + "_" + new Random().nextInt()+ DateConvert.formatDateToString(new Date(), DateStyle.YYYYMMDDHHMMSS) + ".png";path = dir + File.separator + fileName;// 存儲路徑String dirPath = ResourceUtil.getUploadImageRelativeRoot2() + dir;filePath = ResourceUtil.getUploadImageRelativeRoot2() + path;// 創(chuàng)建新的文件boolean resultDir = FileUtil.makedir(dirPath);if (resultDir == true) {LogService.getInstance(this).debug(filePath);File file = new File(filePath);out = new FileOutputStream(file);out.write(b);out.flush();out.close();} else {LogService.getInstance(this).error("建立文件夾" + dir + "失敗,完整路徑為:dirPath");}} catch (Exception e) {e.printStackTrace();}return ResourceUtil.getUploadImgRelativeRoot()+path;}在存儲路徑這個地方又調(diào)用ResourceUtil下的getUploadImageRelativeRoot2()
來獲取存儲圖片的相對路徑。
public static final String getUploadImageRelativeRoot2() {return System.getProperty("catalina.home")+File.separator+"webapps"+File.separator+"img"+File.separator;}jsp頁面代碼
?<img src="${ctx}/{{html themeImageUrl}}">效果
記得要配置Tomcat下的server.xml路徑映射。
?
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的SSM+BJUI实现以Base64方式上传照片的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux服务器上配置Tomcat的do
- 下一篇: 前端解密后台加密算法优化思想