ext上传文件到mysql上
不废话,上代码:
controller如下:
/** * 上传附件 * @param request * @param baseBlob * @param response */ @RequestMapping(value="/uploadSeal",method=RequestMethod.POST) @ResponseBody public void addBaseBlob(HttpServletRequest request,Seal seal,HttpServletResponse response,@RequestParam(required=false) String sealId){ int flag=0; try { request.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request; MultipartFile multipartFile = multipartRequest.getFile("file"); // 上传的文件名 //需要保存 String uploadFileName = multipartFile.getOriginalFilename(); // 获取文件后缀名 //需要保存 String fileType = StringUtils.substringAfterLast(uploadFileName, "."); if("PNG".equalsIgnoreCase(fileType)||"JPEG".equalsIgnoreCase(fileType)||"JPG".equalsIgnoreCase(fileType)){ if(multipartFile!=null&&!"".equals(multipartFile.getName())){ File file = new File(request.getSession().getServletContext() .getRealPath("WEB-INF"+File.separator+"upload"), multipartFile.getOriginalFilename()); // 判断文件夹是否存在,不存在则创建 if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } try { String userId=request.getParameter("userId"); FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file); seal.setUpdateUser(((BaseUsers)request.getSession().getAttribute(WebConstants.CURRENT_USER)).getUserId()); seal.setUpdateTime(new Date()); seal.setSealImage(FileDigest.getBytesFromFile(file)); if(StringUtils.isNotBlank(sealId)){ seal.setId(sealId); flag = sealService.update(seal); }else{ flag=sealService.insert(seal); } } catch (IOException e) { e.printStackTrace(); flag=0; }finally{ file.delete(); } } response.setContentType("text/html;charset=utf-8;"); try { if(flag==1) response.getWriter().write("{success:true,msg:\""+seal.getId()+"\"}"); else response.getWriter().write("{success:false,msg:\"上传失败!\"}"); } catch (IOException e) { e.printStackTrace(); }finally{ try { response.getWriter().flush(); response.getWriter().close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }else{ response.setContentType("text/html;charset=utf-8;"); try { response.getWriter().write("{success:false,msg:\"格式不正确!\"}"); response.getWriter().flush(); response.getWriter().close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
前台ext如下:
Ext.ns('Ext.seal') Ext.seal.SealUploadWindow = Ext.extend(Ext.Window, { store : null, /* 保存路径 */ uploadUrl : null, //grid : null, title : '上传印章', constructor : function(_config) { Ext.apply(this, _config || {}); this.myform = new Ext.FormPanel({ fileUpload : true, // 默认为图片上传 id : Ext.id(), baseCls : 'x-plain',// 基本效果为纯色效果 bodyStyle : 'padding-top:10px;padding-left:0px;', closealbe : true, // 里面组件的布局方式 // layout : 'fit', height : 400, items : [{ labeWidth : 80, xtype : 'textfield', name : 'file', inputType : 'file', allowBlank : false, width : 200, fieldLabel : '上传印章' },{ xtype : 'textfield', name : 'sealId', hidden : true }] }); this.url = { uploadUrl : ctx+'/seal/uploadSeal' } Ext.seal.SealUploadWindow.superclass.constructor.call(this, { width : 350, height : 150, title : '上传印章', frame : true, // 可以关闭 closable : true, // 关闭 按钮 销毁 窗口并销毁所以子控件。这使得Window对象和它的子控件不可 复用. // 如果想复用Window, 设置 closeAction: 'hide' , //closeAction : 'close', // 打开window页面在window页面加了个遮罩层 modal : true, // 纯色效果 plain : true, // 里面组件的布局方式 layout : 'fit', items : [this.myform], buttons : [{ text : '上传印章', scope : this, handler : this.uploadPhoto }, { text : '重置印章', scope : this, handler : function() { this.myform.getForm().reset(); } }, { text : '关闭', iconCls:'cancel', scope : this, handler : function() { this.hide(); } }] }); }, // 提交表单 uploadPhoto : function() { if (this.myform.getForm().isValid()) { this.myform.getForm().submit({ url : this.url.uploadUrl, method : 'post', waitMsg : '印章上传中...', scope : this, success : function(form, action) { Ext.Msg.alert('提示', '上传成功!', function() { var sealId = action.result.msg; this.myform.getForm().findField('sealId').setValue(sealId); this.hide(); }, this); }, failure : function(form, action) { Ext.Msg.alert('提示', action.result.msg, function() { }, this); } }); } } });
formpanel:
Ext.ns('Ext.seal'); Ext.seal.SealFormPanel = new Ext.extend(Ext.form.FormPanel, { sealId:null, constructor : function(_config) { if (_config == null) { _config = {}; } this.imgBox = new Ext.BoxComponent({ xtype : 'box', id : 'browseImage', name : 'photopath', anchor : '20%', height : 120, width : 240, autoEl : { tag : 'img', src : '', style : 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);', complete : 'off' } }); this.store = new Ext.data.Store(); this.tempID = Ext.id(); this.labeID = Ext.id(); Ext.apply(this, _config); this.contentPanelId = Ext.id(); Ext.seal.SealFormPanel.superclass.constructor.call(this, { labelWidth : 80, frame : true, border : false, bodyStyle : 'border:0px;', defaults : { bodyStyle : 'border:0px;', width : 560 }, items : [{ layout : 'column', xtype : 'fieldset', title : '详细信息', items : [{ columnWidth : .5, defaults : { // 设置默认类型 xtype : 'textfield', // 自动调整宽度 anchor : '90%', disabledClass : 'txtDisabled' }, layout : 'form', autoHeight : true, // 分栏中的元素 items : [{ name : 'id', xtype : 'textfield', hidden : true }, { fieldLabel : '印章名称', xtype : 'textfield', name : 'sealName', allowBlank : false, blankText : '请输入印章名称' }, { fieldLabel : '备注', xtype : 'textarea', name : 'remark' },{ xtype:'hidden', name:'sealId' }] }, { columnWidth : .5, defaults : { // 设置默认类型 xtype : 'textfield', // 自动调整宽度 anchor : '90%', disabledClass : 'txtDisabled' }, layout : 'form', autoHeight : true, style : 'margin-left:20px', // 分栏中的元素 items : [this.imgBox,{ xtype : 'button', text : '上传印章', allowBlank : false, anchor : '20%', scope:this, handler : this.uploadWindow }] }] }], // items : [this.imgBox,{ // xtype : 'button', // text : '上传印章', // allowBlank : false, // anchor : '20%', // scope:this, // handler : this.uploadWindow // },{ // name : 'id', // xtype : 'textfield', // hidden : true // }, { // fieldLabel : '印章名称', // xtype : 'textfield', // name : 'sealName', // allowBlank : false, // blankText : '请输入印章名称' // }, { // fieldLabel : '备注', // xtype : 'textarea', // name : 'remark' // },{ // xtype:'hidden', // name:'sealId' // } // ] }); }, uploadWindow : function (){ if (this.myUploadWin == null) { this.myUploadWin = new Ext.seal.SealUploadWindow({ }); } this.myUploadWin.on('show', function(win) { win.myform.getForm().reset(); if(this.sealId){ win.myform.getForm().findField('sealId').setValue(this.sealId); } }, this); this.myUploadWin.show(); this.myUploadWin.on('hide', function(win) { var sealId2 = win.myform.getForm().findField('sealId').getValue(); this.getForm().findField('sealId').setValue(sealId2); Ext.getCmp('browseImage').getEl().dom.src=ctx+"/seal/download?sealId="+sealId2+"&thisTime="+Date.parse(new Date()); }, this); } })
winpanel:
Ext.ns('Ext.seal'); Ext.seal.SealWin = Ext.extend(Ext.Window, { store : null, saveUrl : null, sealId:null, constructor : function(config) { if (config == null) { config = {} } Ext.apply(this, config); this.formPanel = new Ext.seal.SealFormPanel({ sealId:this.sealId }); Ext.seal.SealWin.superclass.constructor.call(this, { width : 600, height : 280, closeAction : 'hide', plain : true, modal : true, resizable : true, layout:'fit', items : [this.formPanel], buttons : [{ text : '保存', scope : this, handler : this.save }, { text : '重置', scope : this, handler : this.reset }] }); }, save : function() { var form = this.formPanel.getForm(); var sealId = form if (!form.isValid()) { return; } // 发送请求 this.formPanel.getForm().submit({ url : this.saveUrl, method:'post', success : function(form,action) { Ext.MessageBox.alert('提示',action.result.msg,function(){ this.store.reload(); this.hide(); },this); }, scope:this }); }, loadRecord : function(record) { this.formPanel.getForm().loadRecord(record); }, reset : function() { this.formPanel.getForm().reset(); } });
GridPanel:
Ext.ns('Ext.seal'); Ext.seal.SealGridPanel= Ext.extend(Ext.grid.GridPanel, { actionJson : null, pageSize : 20, constructor : function(_config) { Ext.apply(this, _config || {}); this.Url = { allUrl : ctx + '/seal/queryListForPage', insertUrl : ctx + '/seal/insert', deleteUrl : ctx + '/seal/delete', updateUrl : ctx + '/seal/update', findByIdUrl:ctx + '/seal/getSeal', isEnableOrNot:ctx + '/seal/isEnableOrNot' }; /** 顶部工具栏 */ this.actionToolBar = new Ext.Toolbar({ items:[new Ext.Action({ text : '新增', scope:this, handler : this.addWindow }),'-',new Ext.Action({ text : '修改', scope:this, handler : this.modifyWindow }),'-',new Ext.Action({ text : '删除', scope:this, handler : this.deleteWindow }),'-',new Ext.Action({ text:'启用', scope:this, handler:this.isEnableTrue }),'-',new Ext.Action({ text:'停用', scope:this, handler:this.isEnableFalse })] }); /** 顶部工具栏*/ // this.actionToolBar = new Ext.ActionToolbar({ // actionPanel : this, // actionJson : this.actionJson, // deleteFunction : this.deleteWindow, // addFunction : this.addWindow, // editFunction : this.modifyWindow // // }); this.store = new Ext.data.JsonStore({ baseParams : { start : 0, limit : this.pageSize }, url : this.Url.allUrl, root : 'rows', // Json中的列表数据根节点 totalProperty : 'results', fields : ['id', 'updateUser', 'realName','sealName','remark','isEnable','sealImage',{ name : 'updateTime', type : 'date', dateFormat : 'time' }] }); /** 基本信息-选择模式 */ this.selModel = new Ext.grid.CheckboxSelectionModel({ singleSelect:true, // listeners : { // // 'rowselect' : function(selectionModel, rowIndex, record) { // this.actionToolBar.enableEditDelete(); // }, // 'rowdeselect' : function(selectionModel, rowIndex, // record) { // if (!selectionModel.hasSelection()) { // this.actionToolBar.disableEditDelete(); // } // }, // scope : this // } }); this.colModel = new Ext.grid.ColumnModel([this.selModel,{ header : '主键', dataIndex : 'id', hidden : true },{ header : '印章名称', dataIndex : 'sealName', width : 150 },{ header : '启用/停用', dataIndex : 'isEnable', width : 150, renderer:function(value){ if(value==1){ return "启用"; }else if(value==0){ return "停用"; } return value; } },{ header : '修改人', dataIndex : 'realName', width : 150 },{ header : '修改时间', dataIndex : 'updateTime', width : 150, renderer : Ext.util.Format.dateRenderer('Y-m-d H:i:s') },{ header : '备注', dataIndex : 'remark', width : 150 },{ header : '印章', dataIndex : 'sealImg', width:200, renderer:function(value,metc,record){ return "<img src="+ctx+"/seal/download?sealId="+record.data.id+"&thisTime="+Date.parse(new Date())+" />"; //return ctx+"/seal/download?sealId="+record.data.id; } }]); this.bbar = new Ext.PagingToolbar({ pageSize : this.pageSize, store : this.store, displayInfo : true }); Ext.seal.SealGridPanel.superclass.constructor.call(this, { store : this.store, cm : this.colModel, sm : this.selModel, tbar : this.actionToolBar, bbar : this.bbar, loadMask : true }); this.on('rowdblclick', this.readSeal, this); this.store.load(); }, addWindow : function() { var record = this.getSelectionModel().getSelected(); if (this.addWin == null) { this.addWin = new Ext.seal.SealWin({ saveUrl : this.Url.insertUrl, store : this.store }); this.addWin.setTitle("新增印章"); } this.addWin.reset(); this.addWin.show(); this.addWin.on('show', function(win) { Ext.getCmp('browseImage').getEl().dom.src=''; }, this); }, modifyWindow : function() { var record = this.getSelectionModel().getSelected(); if (record) { if (this.editWin == null) { this.editWin = new Ext.seal.SealWin({ saveUrl : this.Url.updateUrl, store : this.store, sealId:record.data.id }); this.editWin.setTitle("修改印章"); } this.editWin.reset(); this.editWin.show(); this.editWin.on('show', function(win) { Ext.getCmp('browseImage').getEl().dom.src=ctx+"/seal/download?sealId="+record.data.id+"&thisTime="+Date.parse(new Date()); }, this); this.editWin.loadRecord(record); } else { Ext.MessageBox.alert('提示', '请选中一条记录!'); } }, deleteWindow : function() { /** 选中的记录 */ var record = this.getSelectionModel().getSelected(); if(!record){ Ext.MessageBox.alert('提示', '请选中一条记录!'); return; } Ext.MessageBox.confirm('提示', '您确定要删除选中记录吗?', function(btn) { if (btn == 'yes') { Ext.Ajax.request({ url : this.Url.deleteUrl, method : 'post', params : { id : record.data.id }, success : function(response, options) { var text = Ext.util.JSON.decode(response.responseText); Ext.MessageBox.alert('提示', text.msg,function(){ if(text.success){ this.store.reload(); } },this); }, failure : function(response, options) { Ext.MessageBox.alert('提示', '请求失败!'); }, scope : this }); } }, this); }, /** 查看印章 */ readSeal : function(grid, rowIndex, e) { var rec = grid.getStore().getAt(rowIndex); if (rec == undefined) { Ext.Msg.alert("提示", "每次只能且必须查看一条记录"); } else { if (this.readWin == null) { this.readWin = new Ext.seal.SealReadWindow({ sealId:rec.data.id }); this.readWin.setTitle('查看详细'); } this.readWin.show(); Ext.Ajax.request({ url : this.Url.findByIdUrl, method : 'post', params : { sealId : rec.data.id }, success : function(response, opts) { var content = Ext.decode(response.responseText); this.readWin.loadSeal(content); }, scope : this }); } }, /**启用*/ isEnableTrue:function(){ var record = this.getSelectionModel().getSelected(); if(!record){ Ext.MessageBox.alert('提示', '请选中一条记录!'); return; }else if(record.data.isEnable==1){ Ext.MessageBox.alert('提示','选中行已经启用!'); return; } Ext.Ajax.request({ url : this.Url.isEnableOrNot, method : 'post', params : { id : record.data.id, isEnable:1 }, success : function(response, options) { var text = Ext.util.JSON.decode(response.responseText); Ext.MessageBox.alert('提示', text.msg,function(){ if(text.success){ this.store.reload(); } },this); }, failure : function(response, options) { Ext.MessageBox.alert('提示', '请求失败!'); }, scope : this }); }, /**停用*/ isEnableFalse:function(){ var record = this.getSelectionModel().getSelected(); if(!record){ Ext.MessageBox.alert('提示', '请选中一条记录!'); return; }else if(record.data.isEnable==0){ Ext.MessageBox.alert('提示','选中行已经停用!'); return; } Ext.Ajax.request({ url : this.Url.isEnableOrNot, method : 'post', params : { id : record.data.id, isEnable:0 }, success : function(response, options) { var text = Ext.util.JSON.decode(response.responseText); Ext.MessageBox.alert('提示', text.msg,function(){ if(text.success){ this.store.reload(); } },this); }, failure : function(response, options) { Ext.MessageBox.alert('提示', '请求失败!'); }, scope : this }); } });
extreturn实体类:
package cn.edu.hbcf.common.vo; /** * Ext Ajax 返回对象 * * @author LiPenghui * @date 2012-02-21 19:30:00 * */ public class ExtReturn { private boolean success; // 是否成功 private Object msg; // 返回消息 private Object otherObject;// 其他对象 public ExtReturn() { } /** * 是否更新成功的构造方法 * * @param success * 是否成功 * @param msg * 消息 */ public ExtReturn(boolean success, Object msg) { this.success = success; this.msg = msg; this.otherObject = ""; } /** * 是否更新成功的构造方法 * * @param success * 是否成功 * @param msg * 消息 * @param otherObject * 其他对象 */ public ExtReturn(boolean success, Object msg, Object otherObject) { this.success = success; this.msg = msg; this.otherObject = otherObject; } /** * 异常时的构造函数 * * @param errormsg * 异常消息 */ public ExtReturn(Object errormsg) { this.success = false; this.msg = false; this.otherObject = ""; } /** * 判断是否成功 * * @return */ public boolean isSuccess() { return success; } /** * 设置返回是否成功的状态 * * @param success */ public void setSuccess(boolean success) { this.success = success; } /** * 设置其他对象 * * @return */ public Object getOtherObject() { return otherObject; } /** * 获取其他对象 * * @param otherObject */ public void setOtherObject(Object otherObject) { this.otherObject = otherObject; } /** * 获取返回的消息 * * @return */ public Object getMsg() { return msg; } /** * 设置返回的消息 * * @param msg */ public void setMsg(Object msg) { this.msg = msg; } }
文件下载controller:
/** * 下载附件 * @param response * @param request * @param blobId 附件主键 * @throws UnsupportedEncodingException */ @RequestMapping("/download") public void download (HttpServletResponse response,HttpServletRequest request,String sealId,String thisTime) throws UnsupportedEncodingException{ Seal seal = sealService.getSeal(sealId); InputStream inputStream=new ByteArrayInputStream(seal.getSealImage()); byte[] b = new byte[1024]; int len = -1; OutputStream out = null; String filename=""; if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") >0) filename = URLEncoder.encode(filename, "UTF-8");//IE浏览器 else filename = new String(filename.getBytes("UTF-8"), "ISO8859-1"); response.reset();//清除首部的空白行 //下载的文件内容 // response.setContentType("application/x-msdownload"); // response.setContentType("text/html;charset=utf-8;"); response.setContentType("image/jpeg;charset=utf-8"); //下载的文件头部内容(自动下载) // response.setHeader("Content-Disposition", "attachment;filename=" + filename.replace(" ", "_") ); //输出文件内容 response.setHeader("Content-type", "attachment;filename=" + filename.replace(" ", "_") ); // response.setHeader("Connection", "close"); try { while ((len = inputStream.read(b, 0, 1024)) != -1) { out = response.getOutputStream(); out.write(b, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e1) { e1.printStackTrace(); } if(inputStream!=null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
/** * 下载附件 * @param response * @param request * @param blobId 附件主键 * @throws UnsupportedEncodingException */ @RequestMapping("/download") public void download (HttpServletResponse response,HttpServletRequest request,String sealId,String thisTime) throws UnsupportedEncodingException{ Seal seal = sealService.getSeal(sealId); InputStream inputStream=new ByteArrayInputStream(seal.getSealImage()); byte[] b = new byte[1024]; int len = -1; OutputStream out = null; String filename=""; if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") >0) filename = URLEncoder.encode(filename, "UTF-8");//IE浏览器 else filename = new String(filename.getBytes("UTF-8"), "ISO8859-1"); response.reset();//清除首部的空白行 //下载的文件内容 // response.setContentType("application/x-msdownload"); // response.setContentType("text/html;charset=utf-8;"); response.setContentType("image/jpeg;charset=utf-8"); //下载的文件头部内容(自动下载) // response.setHeader("Content-Disposition", "attachment;filename=" + filename.replace(" ", "_") ); //输出文件内容 response.setHeader("Content-type", "attachment;filename=" + filename.replace(" ", "_") ); // response.setHeader("Connection", "close"); try { while ((len = inputStream.read(b, 0, 1024)) != -1) { out = response.getOutputStream(); out.write(b, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e1) { e1.printStackTrace(); } if(inputStream!=null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
mapper:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.edu.hbcf.plugin.seal.dao.SealMapper"> <!-- 查询所有的印章管理数据 --> <select id="queryListForPage" resultType="cn.edu.hbcf.plugin.seal.pojo.Seal" parameterType="cn.edu.hbcf.common.vo.Criteria"> SELECT l.id id, l.update_user updateUser, l.update_time updateTime, l.seal_name sealName, l.remark remark, l.is_enable isEnable, l.seal_image sealImage, s.real_name realName FROM seal l LEFT JOIN base_users s ON l.update_user = s.user_id WHERE l.seal_name IS NOT NULL AND seal_name != '' <if test="condition.limit != null"> <![CDATA[ limit #{condition.start},#{condition.limit} ]]> </if> </select> <!-- 查询所有的印章管理数据的总数 --> <select id="getTotalCount" resultType="int" parameterType="cn.edu.hbcf.common.vo.Criteria"> SELECT count(*) FROM seal l </select> <!-- 新增印章数据 --> <insert id="insert" parameterType="cn.edu.hbcf.plugin.seal.pojo.Seal"> <selectKey resultType="String" keyProperty="id" order="BEFORE"> select replace(uuid(), '-', '') from dual </selectKey> INSERT INTO seal(id,update_user,update_time,seal_name,remark,is_enable,seal_image) VALUES(#{id},#{updateUser},#{updateTime},#{sealName},#{remark},#{isEnable},#{sealImage}) </insert> <!-- 修改印章数据 --> <update id="update" parameterType="cn.edu.hbcf.plugin.seal.pojo.Seal"> UPDATE seal SET update_user=#{updateUser},update_time=#{updateTime}, <if test="sealName!=null">seal_name=#{sealName},</if> <if test="remark!=null">remark=#{remark},</if> <if test="isEnable!=null">is_enable=#{isEnable},</if> <if test="sealImage!=null">seal_image=#{sealImage}</if> WHERE id=#{id} </update> <!-- 批量删除印章数据 --> <delete id="delete"> delete from seal <where> id in <foreach collection="ids" item="item" index="index" open="(" separator="," close=")">#{item}</foreach> </where> </delete> <!-- 新增印章图片到数据库中 --> <insert id="insertSeal" parameterType="String"> <selectKey resultType="String" keyProperty="id" order="BEFORE"> select replace(uuid(), '-', '') from dual </selectKey> insert into seal(id,seal_image) values(#{id},#{sealImage}) </insert> <!-- 修改印章图片 --> <update id="updateSeal" parameterType="cn.edu.hbcf.plugin.seal.pojo.Seal"> update seal set seal_image=#{sealImage} where id=#{id} </update> <!-- 根据Id查询信息--> <select id="getSeal" resultType="cn.edu.hbcf.plugin.seal.pojo.Seal" parameterType="java.lang.String"> SELECT l.id id, l.update_user updateUser, l.update_time updateTime, l.seal_name sealName, l.remark remark, l.is_enable isEnable, l.seal_image sealImage, s.real_name realName FROM seal l LEFT JOIN base_users s ON l.update_user = s.user_id WHERE l.id = #{id} </select> <!-- 启用或者停用 --> <update id="isEnableOrNot" parameterType="cn.edu.hbcf.plugin.seal.pojo.Seal"> UPDATE seal SET is_enable=#{isEnable} WHERE id=#{id} </update> </mapper>