後臺服務端接收文件的代碼:html
/** * 後臺上傳文件處理Action */ @RequestMapping(value = "/uploadFile", method=RequestMethod.POST) public void uploadFile(@RequestParam(value="file",required=true) MultipartFile file ,HttpServletResponse response) { ModelMap modelMap = new ModelMap(); String savePath = "D:/tmp/";//保存路徑
try { String fileName = file.getName(); File saveFile = new File(savePath); if(!saveFile.exists()){ saveFile.mkdirs(); } saveFile = new File(savePath, fileName); file.transferTo(saveFile); modelMap.addAttribute("success", true); } catch (Exception e) { modelMap.addAttribute("success", false); modelMap.addAttribute("message", "保存失敗:"+e.getMessage()); } JSONSerializer serializer = new JSONSerializer(); String result = serializer.serialize(modelMap); //ExtJS上傳須要用這種方法實現返回 response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); writer.write(result); writer.flush(); writer.close(); }
剛開始使用 return modelMap 返回信息,可是前臺就是接收不到數據,最後看API後使用PrintWriter來搞定。app
附上前臺上傳窗口代碼:ui
UploadForm = Ext.extend(Ext.Window,{ constructor : function(a){ Ext.applyIf(this,a); this.initUIComponents(); UploadForm.superclass.constructor.call(this,{ layout : 'fit', modal : true,//遮罩層 constrain : true, width : 500, height : 200, title : '選擇上傳文件窗口', items : this.formPanel, buttonAlign : 'center', keys : [{ key : Ext.EventObject.ENTER, scope: this, fn: this.uploadFile }], buttons : [{ text : '保存', scope : this, iconCls : "btn-save", handler: this.uploadFile },{ text : '取消', scope : this, iconCls : "btn-cancel", handler : function(){ this.close(); } }] }); }, initUIComponents : function(){ this.formPanel = new Ext.FormPanel({ layout : 'form', fileUpload: true, border : false, method:'POST', enctype:'multipart/form-data', bodyStyle : 'padding: 10px 10px 0 10px;', url : _ctx + '/fuile/uploadFile.do', defaults : { anchor : '100%' }, labelAlign : 'right', items : [ {xtype : 'hidden',name : 'userId',value : this.userId}, Ext.Util.buildColumnForm(1,'textfield',{ fieldLabel : '備註信息', name : 'remark', allowBlank : false, maxLength : 100, maxLengthText : '信息長度小於等於100個字符' }), { xtype: 'fileuploadfield', id: 'form_file', fieldLabel : '腳本上傳', name : 'file',//後臺接收 emptyText: '請上傳word文檔', buttonText: '', regex : /\.(doc|docx)$/, regexText : "請上傳word文檔", buttonCfg: { iconCls: 'btn-upload-icon' } } ] }); }, uploadFile : function(){ var win = this; var formFile = Ext.getCmp('form_file').getValue(); if(this.formPanel.getForm().isValid()){ if(formFile==''){ Ext.Msg.alert("操做提示:", "請上傳word文件而後保存"); return; } this.formPanel.getForm().submit({ url: ctx + '/file/uploadFile.do', waitMsg: '正在保存...', success : function(form, action){ var result = Ext.decode(action.response.responseText); Ext.Msg.alert(result.message, ""); win.close(); }, failure: function(form, action) { var result = Ext.decode(action.response.responseText); Ext.Msg.alert("錯誤提示", result.message); } }); } } });
調用方法 new UploadForm({userId : '34567'}).show();