html页面代码
<form role="form" class="form-horizontal" name="theMicroForm" ng-submit="submitMicroFormEdit(theMicroForm)" enctype="multipart/form-data" novalidate> <div class="modal-body"> <div class="form-group" ng-class="{'has-error':theMicroForm.mcName.$dirty && theMicroForm.mcName.$invalid, 'has-success':theMicroForm.mcName.$valid}"> <label class="col-sm-2 control-label" > {{'payment.name' | translate}} </label> <div class="col-sm-6"> <input type="text" id="mcName" name="mcName" class="form-control" ng-model="formData.mcName" maxlength="30" required/> <span class="symbol required"></span> </div> <div class="col-sm-4"> <span class="error text-small block" ng-if="theMicroForm.mcName.$dirty && theMicroForm.mcName.$error.required">{{'payment.name' | translate}}{{'form.validate_prompt.not_null' | translate}}</span> </div> </div> <div class="form-group" ng-class="{'has-error':theMicroForm.mcPath.$dirty && theMicroForm.mcPath.$invalid, 'has-success':theMicroForm.mcPath.$valid}"> <label class="col-sm-2 control-label" > {{'two-dimentsional.img' | translate}} </label> <div class="col-sm-6"> <input type="file" id="mcPath" name="mcImageTmp" class="form-control" ng-model="formData.mcPath"/> <span class="symbol required"></span> </div> <div class="col-sm-4"> <span class="error text-small block" ng-if="theMicroForm.mcPath.$dirty && theMicroForm.mcPath.$error.required">{{'two-dimentsional.img' | translate}}{{'form.validate_prompt.not_null' | translate}}</span> </div> </div> <div class="form-group" ng-class="{'has-error':theMicroForm.mcType.$dirty && theMicroForm.mcType.$invalid, 'has-success':theMicroForm.mcType.$valid}"> <label class="col-sm-2 control-label" > {{'enterprise.two-dimension.type' | translate}} </label> <div class="col-sm-6"> <select class="cs-select cs-skin-elastic" id="mcType" name="mcType" ng-model="formData.mcType" required> <option value="02TA">{{'pay.alipay.enterprise' | translate}}</option> <option value="02TW">{{'pay.weChat' | translate}}</option> </select> <span class="symbol required"></span> </div> <div class="col-sm-4"> <span class="error text-small block" ng-if="theMicroForm.mcType.$dirty && theMicroForm.mcType.$error.required">{{'enterprise.two-dimension.type' | translate}}{{'form.validate_prompt.not_null' | translate}}</span> </div> </div> <div class="form-group" ng-class="{'has-error':theMicroForm.mcRemarks.$dirty && theMicroForm.mcRemarks.$invalid, 'has-success':theMicroForm.mcRemarks.$valid}"> <label class="col-sm-2 control-label" > {{'pub.remark' | translate}} </label> <div class="col-sm-6"> <textarea rows="2" class="form-control" name="mcRemarks" id="mcRemarks" ng-model="formData.mcRemarks" ng-maxlength="100" placeholder="{{'pub.remark' | translate}}">{{synopsis}}</textarea> </div> </div> </div> <div class="modal-footer"> <button class="btn btn-primary" type="submit" id="submitMicroEditId">{{'button.ok' | translate}}</button> <button class="btn btn-primary btn-o" type="button" ng-click="cancel()">{{'button.cancel' | translate}}</button> </div> </form>js端代码提交后台
app.controller("addMicroCodeCtrl",["$modalInstance","$scope","$http","SweetAlert","$translate","$rootScope",function($modalInstance,$scope,$http,SweetAlert,$translate,$rootScope){ $translate('enterprise.two-dimension.add').then(function(result){ $scope.modalTitle = result; }); $scope.submitMicroFormEdit = function(form) { if (form.$invalid) { var field = null, firstError = null; for (field in form) { if (field[0] != '$') { if (firstError === null && !form[field].$valid) { firstError = form[field].$name; } if (form[field].$pristine) { form[field].$dirty = true; } } } angular.element('.ng-invalid[name=' + firstError + ']').focus(); return; } else { //防止表单重提交 $("#submitMicroEditId").attr("disabled", true); $.ajaxFileUpload({ async: true, url: "/microCodeController/add", type: 'post', dataType: 'JSON', mcPath:'mcPath', fileElementId:'mcPath', data: { mcName:$("#mcName").val(), mcType:$("#mcType").val(), mcRemarks:$("#mcRemarks").val(), mcPath: $("#mcPath").val(), mcImage: $("#mcPath").val() }, success: function(data){ //防止表单重提交 $("#submitEditId").attr("disabled", true); var jsonobj= data; if(jsonobj.code=='200'){ $translate('dialog.update_success').then(function(msg) { SweetAlert.swal({ title: msg, type: 'success' }); $modalInstance.close(); }) } } }); } }; $scope.cancel = function () { $modalInstance.close(); }; }]);
前端上传文件依赖的js文件
<script src="/js/cms/ajaxfileupload.js"></script>
后端controller方法jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); if(typeof uri== 'boolean'){ io.src = 'javascript:false'; } else if(typeof uri== 'string'){ io.src = uri; } } else { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; } io.style.position = 'absolute'; io.style.top = '-1000px'; io.style.left = '-1000px'; document.body.appendChild(io); return io }, createUploadForm: function(id, fileElementId, data) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); var oldElement = $('#' + fileElementId); var newElement = $(oldElement).clone(); $(oldElement).attr('id', fileId); $(oldElement).before(newElement); $(oldElement).appendTo(form); //增加文本参数的支持 if (data) { for (var i in data) { $('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); } } //set attributes $(form).css('position', 'absolute'); $(form).css('top', '-1200px'); $(form).css('left', '-1200px'); $(form).appendTo('body'); return form; }, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = new Date().getTime() var form = jQuery.createUploadForm(id, s.fileElementId, s.data); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id; // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } var requestDone = false; // Create the request object var xml = {} if ( s.global ) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var uploadCallback = function(isTimeout) { var io = document.getElementById(frameId); try { if(io.contentWindow) { xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument) { xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) { jQuery.handleError(s, xml, null, e); } if ( xml || isTimeout == "timeout") { requestDone = true; var status; try { status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if ( status != "error" ) { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData( xml, s.dataType ); // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status ); // Fire the global callback if( s.global ) jQuery.event.trigger( "ajaxSuccess", [xml, s] ); } else jQuery.handleError(s, xml, status); } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if( s.global ) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); // Process result if ( s.complete ) s.complete(xml, status); jQuery(io).unbind() setTimeout(function() { try { $(io).remove(); $(form).remove(); } catch(e) { jQuery.handleError(s, xml, null, e); } }, 100) xml = null } } // Timeout checker if ( s.timeout > 0 ) { setTimeout(function(){ // Check to see if the request is still happening if( !requestDone ) uploadCallback( "timeout" ); }, s.timeout); } try { // var io = $('#' + frameId); var form = $('#' + formId); $(form).attr('action', s.url); $(form).attr('method', 'POST'); $(form).attr('target', frameId); if(form.encoding) { form.encoding = 'multipart/form-data'; } else { form.enctype = 'multipart/form-data'; } $(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } if(window.attachEvent){ document.getElementById(frameId).attachEvent('onload', uploadCallback); } else{ document.getElementById(frameId).addEventListener('load', uploadCallback, false); } return {abort: function () {}}; }, uploadHttpData: function( r, type ) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if (type == "json" || type == "JSON") { var reg = /<pre.+?>(.+)<\/pre>/g; var result = data.match(reg); data = $.parseJSON(RegExp.$1); return data; } // evaluate scripts within html if ( type == "html" ) jQuery("<div>").html(data).evalScripts(); //alert($('param', data).each(function(){alert($(this).attr('value'));})); return data; }, handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context || s, xhr, status, e ); } // Fire the global callback if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); } } });
@RequestMapping(value="add",method = RequestMethod.POST) @ResponseBody public Response add(MultipartFile mcImageTmp,HttpServletRequest request,MicroCode MicroCode) { try { Long hallId = SecurityUtils.getCurrentHallId(request); if(hallId==null) { return Response.error(ApiErrorCode.ERROR_USER_LOG, Constants.DIALOG_ADD_FAIL); } else { MicroCode.setHallId(hallId); } if(mcImageTmp.getSize()>(1024*1024*1000l)){ logger.info("上传图片容量过大!(限1G)"); return Response.error(GlobalEnum.GLOBAL_ENUM_CLIENT_ERROR_CODE.getValue(), SidCustEnum.SID_CRST_ERROR_SID_ERROR_33.getValue()); } if((mcImageTmp!=null)&&(mcImageTmp.getSize()>0)) { File imageFile = new File(MicroCode.getMcImage()); String serviceImage = upImage(mcImageTmp.getInputStream(),imageFile.getName()); MicroCode.setMcPath(serviceImage); } MicroCode.setMcCreatedate(new Date()); MicroCode.setMcUpdatedate(new Date()); microCodeService.insert(MicroCode); } catch(Exception e) { logger.error(e.getMessage()); return Response.error(ApiErrorCode.ERROR_CODE, Constants.DIALOG_ADD_FAIL); } return Response.ok(GlobalEnum.GLOBAL_ENUM_SUCCESS_CODE.getValue(), Constants.DIALOG_ADD_SUCCESS); }
private String upImage(InputStream inputStream,String imageName) { /**服务创建成功后 上传文件 */ SmbUtil smbUtil = new SmbUtil(this.propertiesService.getSmbServerUrl(),"bbp"); String type = ".jpg"; if(imageName.lastIndexOf(".")>0){ type = imageName.substring(imageName.lastIndexOf(".")) ; } imageName = UUID.randomUUID().toString().substring(0,20)+type ; smbUtil.uploadFileByStream(inputStream, imageName); return imageName; }
链接smb上传的utils
/** * SMB文件传输工具类 * Created by terry on 2016/1/7 0007. */ public class SmbUtil { private static final Logger logger = Logger.getLogger(SmbUtil.class); // private static String url = "smb://kenny:123456@192.168.0.50"; private static SmbFile smbFile = null;//Singleton private SmbFileOutputStream smbOut = null; private String url ; private String code_temp = ""; public SmbUtil(String url,String code){ this.url = url ; code_temp = code; init(code); } /** * 初始化链接 * @param code */ public void init(String code) { try { logger.info("开始连接...url:" + url + "/" + code); if (smbFile == null) { smbFile = new SmbFile(url + "/" + code); code_temp = code; smbFile.connect(); } logger.info("连接成功...url:" + url + "/" + code); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 文件上传 * @param inputStream * @param imageName * @return */ public boolean uploadFileByStream (InputStream inputStream,String imageName) { long start = System.currentTimeMillis(); boolean flag = true ; BufferedInputStream bf = null; try { System.out.println("---> "+url +"/"+code_temp+ "/"); this.smbOut = new SmbFileOutputStream(url +"/"+code_temp+ "/" + imageName, false); bf = new BufferedInputStream(inputStream); byte[] bt = new byte[8192]; int n = bf.read(bt); while (n != -1) { this.smbOut.write(bt, 0, n); this.smbOut.flush(); n = bf.read(bt); } logger.info("文件传输结束... 文件传输耗时:"+(System.currentTimeMillis()-start)); } catch (IOException e) { e.printStackTrace(); flag = false ; } finally { try { if (null != this.smbOut) this.smbOut.close(); if (null != bf) bf.close(); } catch (Exception e2) { e2.printStackTrace(); } } return flag; } }