附件上传(包含重命名文件名)
2016-08-10 17:50
411 查看
附件上传
方法1 (包含重命名文件名)
@RequestMapping("/upload") public void upload(HttpServletRequest request,HttpServletResponse response){ String tybh=request.getParameter("tybh")!= null ? request.getParameter("tybh").toString() : ""; String type=request.getParameter("type")!= null ? request.getParameter("type").toString() : ""; System.out.println("tybh:"+tybh+"type:"+type); String realpath=request.getSession().getServletContext().getRealPath("/upload/zhd/"); realpath=realpath+"\\"+type+"\\"+tybh+File.separator; File fileDir = new File(realpath); if(!fileDir .exists() && !fileDir .isDirectory()){ //System.out.println("//不存在"); fileDir.mkdir(); }else{ //System.out.println("//目录存在"); } MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request; Map<String, MultipartFile> map = multipartRequest.getFileMap(); try { for(Map.Entry<String, MultipartFile> entity : map.entrySet()){ MultipartFile mf = entity.getValue(); String fileName = java.net.URLDecoder.decode(mf.getName(),"utf-8"); File uploadFile = new File(realpath + fileName); //FileCopyUtils.copy(mf.getBytes(), uploadFile); //文件重命名 //System.out.println(" 文件名 "+fileName); String [] a=fileName.split("\\."); int num=getMax(realpath); String fileType="."+a[1]; String newFileName=tybh+"_"+num+fileType; // System.out.println("newFileName "+newFileName); File dest = new File(realpath +newFileName); uploadFile.renameTo(dest); FileCopyUtils.copy(mf.getBytes(), dest); } } catch (Exception e) { e.printStackTrace(); } JSONObject jsonObj = new JSONObject(); jsonObj.put("success",true); PrintWriter writer; try { writer = response.getWriter(); writer.write(jsonObj.toString()); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } //获取文件夹中文件个数 private int getMax(String filePath){ File f = new File(filePath); File[] fl = null; int iNum = 0; if(f.isDirectory()){ fl = f.listFiles(); for (int i=0; i < fl.length; i++){ File f2 = fl[i]; if (f2.isFile()){ iNum = iNum + 1; } } } return iNum; }
方法2
@RequestMapping("/upload1") public void upload1(HttpServletRequest request,HttpServletResponse response){ String tybh=request.getParameter("tybh")!= null ? request.getParameter("tybh").toString() : ""; String type=request.getParameter("type")!= null ? request.getParameter("type").toString() : ""; int num=0; CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); if(multipartResolver.isMultipart(request)){ MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; Iterator<String> iter = multiRequest.getFileNames(); while(iter.hasNext()){ MultipartFile file = multiRequest.getFile(iter.next()); if(file != null){ String myFileName = file.getOriginalFilename(); System.out.println("文件名:"+myFileName); if(myFileName.trim() !=""){ //重命名上传后的文件名 String [] a=myFileName.split("\\."); num+=num+1; System.out.println("num: "+num); String fileType="."+a[1]; String newFileName=tybh+"_"+num+fileType; String realpath=request.getSession().getServletContext().getRealPath("/upload/zhd/"); realpath=realpath+"\\"+type+"\\" +newFileName; System.out.println("上传路径 :" + realpath); File localFile = new File(realpath); try { file.transferTo(localFile); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } } } }
前台使用swfupload
一下代码为upload.js
TYBH=null; TYPE=null; var upload=function(){ this.up=function(tybh,type){ TYBH=tybh; TYPE=type; showCwindow(TYBH,TYPE); }; }; var from=null; function showCwindow(tybh,type){ if(from){ from.destory(); cwindow.destory(); } Ext.define('Ext.ux.uploadPanel.UploadPanel',{ extend : 'Ext.grid.Panel', alias : 'widget.uploadpanel', width : 700, height : 300, columns : [ {xtype: 'rownumberer'}, {text: '文件名', width: 100,dataIndex: 'name'}, {text: '自定义文件名', width: 130,dataIndex: 'fileName',editor: {xtype: 'textfield'}}, {text: '类型', width: 70,dataIndex: 'type'}, {text: '大小', width: 70,dataIndex: 'size',renderer:function(v){ return Ext.util.Format.fileSize(v); }}, {text: '进度', width: 130,dataIndex: 'percent',renderer:function(v){ var stml = '<div>'+ '<div style="border:1px solid #008000;height:10px;width:115px;margin:2px 0px 1px 0px;float:left;">'+ '<div style="float:left;background:#FFCC66;width:'+v+'%;height:8px;"><div></div></div>'+ '</div>'+ //'<div style="text-align:center;float:right;width:40px;margin:3px 0px 1px 0px;height:10px;font-size:12px;">{3}%</div>'+ '</div>'; return stml; }}, {text: '状态', width: 80,dataIndex: 'status',renderer:function(v){ var status; if(v==-1){ status = "等待上传"; }else if(v==-2){ status = "上传中..."; }else if(v==-3){ status = "<div style='color:red;'>上传失败</div>"; }else if(v==-4){ status = "上传成功"; }else if(v==-5){ status = "停止上传"; } return status; }}, { xtype:'actioncolumn', width:50, items: [{ //icon: '../../icons/delete.gif', tooltip: 'Remove', handler: function(grid, rowIndex, colIndex) { var id = grid.store.getAt(rowIndex).get('id'); grid.store.remove(grid.store.getAt(rowIndex)); } }] } ], plugins: [ Ext.create('Ext.grid.plugin.CellEditing', { clicksToEdit: 1 }) ], store : Ext.create('Ext.data.JsonStore',{ id:'st1', autoLoad : false, fields : ['id','name','type','size','percent','status','fileName'] }), addFileBtnText : 'Add File', uploadBtnText : 'Upload', removeBtnText : 'Remove All', cancelBtnText : 'Cancel', debug : false, file_size_limit : 100,//MB file_types : '*.*', file_types_description : 'All Files', file_upload_limit : 50, file_queue_limit : 0, post_params : {}, upload_url : 'test.do', flash_url : "../../js/Swfupload/swfupload.swf", flash9_url : "../../js/Swfupload/swfupload_fp9.swf", initComponent : function(){ this.dockedItems = [{ xtype: 'toolbar', dock: 'top', items: [ { xtype:'button', itemId: 'addFileBtn', iconCls : 'add', // id : '_btn_for_swf_', text : this.addFileBtnText },{ xtype: 'tbseparator' },{ xtype : 'button', itemId : 'uploadBtn', iconCls : 'openroomiconinfo', text : this.uploadBtnText, scope : this, handler : this.onUpload },{ xtype: 'tbseparator' },{ xtype : 'button', itemId : 'removeBtn', iconCls : 'del_user', text : this.removeBtnText, scope : this, handler : this.onRemove },{ xtype: 'tbseparator' },{ xtype : 'button', itemId : 'cancelBtn', iconCls : 'cancel', disabled : true, text : this.cancelBtnText, scope : this, handler : this.onCancelUpload } ] }]; this.callParent(); this.down('button[itemId=addFileBtn]').on({ afterrender : function(btn){ var config = this.getSWFConfig(btn); this.swfupload = new SWFUpload(config); Ext.get(this.swfupload.movieName).setStyle({ position : 'absolute', top : 0, left : -2 }); }, scope : this, buffer:300 }); }, getSWFConfig : function(btn){ var me = this; var placeHolderId = Ext.id(); var em = btn.getEl().child('em'); if(em==null){ em = Ext.get(btn.getId()+'-btnWrap'); } em.setStyle({ position : 'relative', display : 'block' }); em.createChild({ tag : 'div', id : placeHolderId }); return { debug: me.debug, flash_url : me.flash_url, flash9_url : me.flash9_url, upload_url: me.upload_url, post_params: me.post_params||{savePath:'upload\\'}, file_size_limit : (me.file_size_limit*1024), file_types : me.file_types, file_types_description : me.file_types_description, file_upload_limit : me.file_upload_limit, file_queue_limit : me.file_queue_limit, button_width: em.getWidth(), button_height: em.getHeight(), button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT, button_cursor: SWFUpload.CURSOR.HAND, button_placeholder_id: placeHolderId, custom_settings : { scope_handler : me }, swfupload_preload_handler : me.swfupload_preload_handler, file_queue_error_handler : me.file_queue_error_handler, swfupload_load_failed_handler : me.swfupload_load_failed_handler, upload_start_handler : me.upload_start_handler, upload_progress_handler : me.upload_progress_handler, upload_error_handler : me.upload_error_handler, upload_success_handler : me.upload_success_handler, upload_complete_handler : me.upload_complete_handler, file_queued_handler : me.file_queued_handler/*, file_dialog_complete_handler : me.file_dialog_complete_handler*/ }; }, swfupload_preload_handler : function(){ if (!this.support.loading) { Ext.Msg.show({ title : '提示', msg : '浏览器Flash Player版本太低,不能使用该上传功能!', width : 250, icon : Ext.Msg.ERROR, buttons :Ext.Msg.OK }); return false; } }, file_queue_error_handler : function(file, errorCode, message){ switch(errorCode){ case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED : msg('上传文件列表数量超限,不能选择!'); break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT : msg('文件大小超过限制, 不能选择!'); break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE : msg('该文件大小为0,不能选择!'); break; case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE : msg('该文件类型不允许上传!'); break; } function msg(info){ Ext.Msg.show({ title : '提示', msg : info, width : 250, icon : Ext.Msg.WARNING, buttons :Ext.Msg.OK }); } }, swfupload_load_failed_handler : function(){ Ext.Msg.show({ title : '提示', msg : 'SWFUpload加载失败!', width : 180, icon : Ext.Msg.ERROR, buttons :Ext.Msg.OK }); }, upload_start_handler : function(file){ var me = this.settings.custom_settings.scope_handler; me.down('#cancelBtn').setDisabled(false); var rec = me.store.getById(file.id); this.setFilePostName(encodeURIComponent(rec.get('fileName'))); }, upload_progress_handler : function(file, bytesLoaded, bytesTotal){ var me = this.settings.custom_settings.scope_handler; var percent = Math.ceil((bytesLoaded / bytesTotal) * 100); percent = percent == 100? 99 : percent; var rec = me.store.getById(file.id); rec.set('percent', percent); rec.set('status', file.filestatus); rec.commit(); }, upload_error_handler : function(file, errorCode, message){ var me = this.settings.custom_settings.scope_handler; var rec = me.store.getById(file.id); rec.set('percent', 0); rec.set('status', file.filestatus); rec.commit(); }, upload_success_handler : function(file, serverData, responseReceived){ var me = this.settings.custom_settings.scope_handler; var rec = me.store.getById(file.id); if(Ext.JSON.decode(serverData).success){ rec.set('percent', 100); rec.set('status', file.filestatus); }else{ rec.set('percent', 0); rec.set('status', SWFUpload.FILE_STATUS.ERROR); } rec.commit(); if (this.getStats().files_queued > 0 && this.uploadStopped == false) { this.startUpload(); }else{ me.showBtn(me,true); } }, upload_complete_handler : function(file){ }, file_queued_handler : function(file){ var me = this.settings.custom_settings.scope_handler; me.store.add({ id : file.id, name : file.name, fileName : file.name, size : file.size, type : file.type, status : file.filestatus, percent : 0 }); }, onUpload : function(){ //alert("count:"+this.store.getCount()); if (this.swfupload&&this.store.getCount()>0) { if (this.swfupload.getStats().files_queued > 0) { this.showBtn(this,false); this.swfupload.uploadStopped = false; this.swfupload.startUpload(); } } }, showBtn : function(me,bl){ me.down('#addFileBtn').setDisabled(!bl); me.down('#uploadBt c1ae n').setDisabled(!bl); me.down('#removeBtn').setDisabled(!bl); me.down('#cancelBtn').setDisabled(bl); if(bl){ me.down('actioncolumn').show(); }else{ me.down('actioncolumn').hide(); } }, onRemove : function(){ var ds = this.store; for(var i=0;i<ds.getCount();i++){ var record =ds.getAt(i); var file_id = record.get('id'); this.swfupload.cancelUpload(file_id,false); } ds.removeAll(); this.swfupload.uploadStopped = false; }, onCancelUpload : function(){ if (this.swfupload) { this.swfupload.uploadStopped = true; this.swfupload.stopUpload(); this.showBtn(this,true); } } }); form=Ext.create('Ext.ux.uploadPanel.UploadPanel',{ // id:'from1', addFileBtnText : '选择文件', uploadBtnText : '上传', removeBtnText : '移除所有文件', cancelBtnText : '取消上传', upload_url : '../../upload.htm?type='+type+'&tybh='+tybh // upload_url : '../../upload.htm' }); Ext.define('MyApp.upfile',{ extend : 'Ext.window.Window', alias : 'widget.uploadpanel', closeAction:'hide',//..... width : 700, height : 300, items:[form] }); var cwindow = Ext.create('MyApp.upfile',{ // id:'cwindow' }).show(); }; var upload=new upload();
引用的一些插件
<link href="../../js/Ext/resources/ext-theme-neptune/ext-theme-neptune-all.css" rel="stylesheet" type="text/css" /> <link href="../../js/CSS/main.css" rel="stylesheet" type="text/css" /> <link href="../../js/CSS/Btn.css" rel="stylesheet" type="text/css" /> <link href="../../CSS/UploadPanel.css"/> <script type="text/javascript" src="../../js/jquery-1.12.1.min.js"></script> <script type="text/javascript" src="../../js/Ext/bootstrap.js"></script> <script src="../../js/Ext/ext-lang-zh_CN.js" type="text/javascript"></script> <script src="../../js/Swfupload/swfupload.js" type="text/javascript"></script> <script type="text/javascript" src="upload.js"></script>
html 页面上的代码
<td>上传多媒体</td> <td > <input type="button" id="dmt" onclick="uploadDmt()"value="上传多媒体"> </td> <td >上传示意图</td> <td > <input type="button" id="syt" onclick="uploadSyt()" value="上传示意图"> </td> function uploadDmt(){ var type="dmt"; upload.up(tybh,type); } function uploadSyt(){ var type="syt"; // upload.showCwindow(tybh,type); upload.up(tybh,type); }
相关文章推荐
- php上传文件名中包含中文字符的附件
- 关于附件上传文件名包含特殊字符引起无发下载附件的问题解决办法
- UEditor的附件上传路径及文件名的问题解决
- zencart上传产品图片后会被重命名修改为保持原文件名
- swfupload 上传中文文件名的附件文件名变乱码
- asp.net 上传或下载当文件名包含有特殊字符"#"的处理
- 上传附件中英文混合的文件名上传
- WordPress 实现附件上传自动重命名但不改变附件标题
- wordpress 上传附件中文文件名乱码解决办法(for Windows)
- asp.net 上传或下载当文件名包含有特殊字符"#"的处理
- dedecms附件上传不自动改名,中文名附件将会改为拼音文件名
- 百度编辑器怎么获取上传附件的文件名
- 【ueditor】上传文件中文文件名失败和在线附件看不到的解决办法
- dedecms附件上传不自动改名(中文名附件将会改为拼音文件名)
- wordpress 上传附件中文文件名乱码解决办法(for Windows){转}
- smtp发送邮件附件时, 如果文件名过长, 会导致附件乱码, 除了重新编译smtp以外, 限制上传文件名长度就是个简便的方法了.
- 上传文件名不可包含中文前端js加入判断
- dedecms附件上传不自动改名,中文名附件将会改为拼音文件名
- javascript判断上传文件名不能包含中文和空格
- 上传或下载当文件名包含有特殊字符"#"的处理