- 浏览: 60699 次
- 性别:
- 来自: 威海
最新评论
一堆代码
fmisfso_edit.jsp
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib uri="/tags/next-web" prefix="next"%> <%@ taglib uri="/tags/next-model" prefix="model"%> <%@page import="org.loushang.next.skin.SkinUtils"%> <%@ page import="org.loushang.bsp.security.context.GetBspInfo" %> <%@ page import="org.loushang.bsp.share.organization.provider.IOrganProvider"%> <%@ page import="org.loushang.bsp.share.organization.OrganFactory"%> <%@ page import="org.loushang.next.dao.DaoFactory"%> <%@ page import="com.sdepci.sso.dao.SdepciSso"%> <%@ page import="com.sdepci.sso.dao.SdepciSsoDao"%> <%@ page import="java.util.Date" %> <%@ page import="java.text.*" %> <% String basePath = request.getContextPath(); String uploadUrl = basePath+"/FileUploadServlet.htm"; %> <html> <head> <title>文件外发申请</title> <next:ScriptManager/> <script> var idField='<%=request.getParameter("dataBean")%>'; var method='<%=request.getParameter("method")%>'; </script> <script type="text/javascript" src="fmisfso_edit.js"></script> <script type="text/javascript" src="<%=SkinUtils.getRootUrl(request)%>jsp/com/sdepci/ucp/action/fileftp/Traverse.js"></script> <link href="<%=basePath%>/jsp/com/sdepci/ucp/ftp/css/default.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="<%=basePath%>/jsp/com/sdepci/ucp/ftp/css/button.css" type="text/css" /> <script type="text/javascript" src="<%=basePath%>/jsp/com/sdepci/ucp/ftp/js/swfupload.js"></script> <script type="text/javascript" src="<%=basePath%>/jsp/com/sdepci/ucp/ftp/js/handlers.js"></script> <script type="text/javascript"> var swfu; window.onload = function () { swfu = new SWFUpload({ upload_url: "<%=uploadUrl.toString()%>", post_params: {"name" : "huliang"}, // File Upload Settings file_size_limit : "1000 MB",// 1000MB file_types : "*.*", file_types_description : "所有文件", file_upload_limit : "0", file_queue_error_handler : fileQueueError, file_dialog_complete_handler : fileDialogComplete,//选择好文件后提交 file_queued_handler : fileQueued, upload_progress_handler : uploadProgress, upload_error_handler : uploadError, upload_success_handler : uploadSuccess, upload_complete_handler : uploadComplete, // Button Settings //button_image_url : "<%=basePath%>/jsp/com/sdepci/ucp/ftp/images/SmallSpyGlassWithTransperancy_17x18.png", button_placeholder_id : "spanButtonPlaceholder", button_width: 180, button_height: 18, button_text : '<span class="button">选择图片 <span class="buttonSmall">(1000 MB Max)</span></span>', button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }', button_text_top_padding: 0, button_text_left_padding: 18, button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT, button_cursor: SWFUpload.CURSOR.HAND, // Flash Settings flash_url : "<%=basePath%>/jsp/com/sdepci/ucp/ftp/js/swfupload.swf", custom_settings : { upload_target : "divFileProgressContainer" }, // Debug Settings debug: false //是否显示调试窗口 }); }; function startUploadFile(){ swfu.startUpload(); } </script> <% //获取当前时间 Date currenttime = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String applyDate = sdf.format(currenttime.getTime()); //以当前时间暂时做为单据编号 SimpleDateFormat codenum = new SimpleDateFormat("yyyyMMddhhmmss"); String codeinfo = codenum.format(currenttime.getTime()); //获取当前登陆人部门ID和部门名称 IOrganProvider organProvider = OrganFactory.getIOrganProvider(); String deptId=GetBspInfo.getBspInfo(request).getDepartmentOrganId(); String depName=organProvider.getLoginUserDepartName(); SdepciSsoDao ssodao=(SdepciSsoDao)DaoFactory.getDao("com.sdepci.sso.dao.SdepciSsoDao"); //获取当前登陆人ID和当前登陆人姓名 String userId=GetBspInfo.getBspInfo(request).getUserId(); SdepciSso userinfo=ssodao.getSdepciSsoByLouShangUserId(userId); String ssouserId=userinfo.getAdAccount(); String userName = GetBspInfo.getBspInfo(request).getUserName(); // String idField=request.getParameter("dataBean"); String method=request.getParameter("method"); %> <script type="text/javascript"> var applyDate='<%=applyDate%>'; var codeInfo='<%=codeinfo%>'; var deptId="<%=deptId%>"; var depName='<%=depName%>'; var userID='<%=ssouserId%>'; var userName='<%=userName%>'; var idField='<%=idField%>'; var method='<%=method%>'; </script> <style type="text/css"> <!-- .titleStyle{ font-size: 24px; font-weight: bold; } --> </style> </head> <body> <model:datasets> <model:dataset id="FmisFsoDataSet" cmd="com.snpit.top.oa.fmis.fso.cmd.FmisFsoQueryCommand" global="true"> <model:record fromBean="com.snpit.top.oa.fmis.fso.dao.FmisFso"></model:record> </model:dataset> <model:dataset id="FmisFsoDetailDataSet" cmd="com.snpit.top.oa.fmis.fso.cmd.FmisFsoDetailCommand" global="true"> <model:record fromBean="com.snpit.top.oa.fmis.fso.dao.FmisFsoDetail"> <model:field name="operation" type="string"/> </model:record> </model:dataset> </model:datasets> <next:Panel> <next:TopBar> <%if(method.equals("INSERT")){%> <next:ToolBarItem iconCls="save" text="提交" handler="saveClick" /> <next:ToolBarItem iconCls="undo" text="关闭" handler="returnClick" /> <%}else if(method.equals("UPDATE")){ %> <next:ToolBarItem iconCls="undo" text="关闭" handler="returnClick" /> <%} %> </next:TopBar> <next:Html> <fieldset> <form id="FmisFsoForm" method="post" dataset="FmisFsoDataSet" onsubmit="return false" style="padding: 5px;" class="L5form"> <p><img src="<%=SkinUtils.getImage(request, "sdepci/logo.gif")%>" width="292" height="37"></p> <p> </p><div align="center" class="titleStyle">文件外发申请</div><p> </p> 状态:<input name="status" field="status" disabled="disabled" style="border: none"/> <table border="0" width="98%" > <tr style="display:none"> <td class="FieldInput">主键:</td> <td class="FieldInput"><input name="fmisFsoId" field="fmisFsoId"/></td> <td class="FieldInput">申请人ID:</td> <td class="FieldInput"><input name="iptPerId" field="iptPerId"/></td> <td class="FieldInput">申请部门ID:</td> <td class="FieldInput"><input name="iptDeptId" field="iptDeptId"/></td> </tr> <tr> <td class="FieldInput" style="text-align: right;">编号:</td> <td class="FieldInput"><input name="fmisFsoCode" field="fmisFsoCode"/></td> <td class="FieldInput" style="text-align: right;">申请时间:</td> <td class="FieldInput"><input name="iptDate" field="iptDate"/></td> </tr> <tr> <td class="FieldInput" style="text-align: right;">申请人:</td> <td class="FieldInput"><input name="iptPer" field="iptPer"/></td> <td class="FieldInput" style="text-align: right;">申请部门:</td> <td class="FieldInput"><input name="iptDept" field="iptDept"/></td> </tr> <tr> <td class="FieldInput" style="text-align: right;">外发事由:</td> <td class="FieldInput" colspan="3"> <textarea rows="4" name="fmisFsoTitle" field="fmisFsoTitle" style="width: 90%"></textarea></td> </tr> <tr style="display:none"> <td class="FieldInput">备注:</td> <td class="FieldInput"><input name="remark" field="remark"/></td> </tr> </table> </form> </fieldset> </next:Html> </next:Panel> <div id="content"> <form class="L5form"> <div style="display: inline; border: solid 1px #7FAAFF; padding: 2px;"> <span id="spanButtonPlaceholder"></span> <input id="btnUpload" type="button" value="上 传" onclick="startUploadFile();" class="btn3_mouseout" onMouseUp="this.className='btn3_mouseup'" onmousedown="this.className='btn3_mousedown'" onMouseOver="this.className='btn3_mouseover'" onmouseout="this.className='btn3_mouseout'"/> <input id="btnCancel" type="button" value="取消所有上传" onclick="cancelUpload();" disabled="disabled" class="btn3_mouseout" onMouseUp="this.className='btn3_mouseup'" onmousedown="this.className='btn3_mousedown'" onMouseOver="this.className='btn3_mouseover'" onmouseout="this.className='btn3_mouseout'"/> </div> </form> <div id="divFileProgressContainer"></div> <div id="thumbnails" style="display:none"> <table id="infoTable" border="1" width="530" style="display: inline; border: solid 1px #7FAAFF; background-color: #C5D9FF; padding: 2px;margin-top:8px;"> </table> </div> </div> <next:FormPanel formId="editForm" border="0"> <next:EditGridPanel id="FmisFsoDetailEditGridPanel" name="FmisFsoDetailEditGridPanel" width="98%" stripeRows="true" height="100%" dataset="FmisFsoDetailDataSet" > <next:Columns> <next:RowNumberColumn width="35" header="序号"/> <next:CheckBoxColumn></next:CheckBoxColumn> <next:Column id="fmisFsoDtlid" header="主键" field="fmisFsoDtlid" width="80" hidden="true"> </next:Column> <next:Column id="fmisFsoId" header="外键" field="fmisFsoId" width="80" hidden="true"> </next:Column> <next:Column id="fileName" header="文件名称" field="fileName" width="300" > </next:Column> <next:Column id="fileSize" header="文件大小" field="fileSize" > </next:Column> <next:Column id="filePath" header="文件路径" field="filePath" hidden="true"> </next:Column> <next:Column id="filetype" header="文件类型" field="filetype" width="125"> <next:TextField /> </next:Column> <next:Column id="operation" header="操作" field="operation" width="125" > </next:Column> </next:Columns> <next:BottomBar> <next:PagingToolBar dataset="FmisFsoDetailDataSet"/> </next:BottomBar> </next:EditGridPanel> </next:FormPanel> </body> </html>
fmisfso_edit.js
/** *事件说明:提交按钮 **/ function saveClick(){ var FmisFsoDataSet = L5.DatasetMgr.lookup("FmisFsoDataSet"); var FmisFsoRecord=FmisFsoDataSet.getCurrent(); var isValidate = FmisFsoDataSet.isValidate(); if(isValidate != true){ L5.Msg.alert("提示",isValidate); return false; } var command = new L5.Command("com.snpit.top.oa.fmis.fso.cmd.FmisFsoCommand"); var FmisFsoDetailRecords = FmisFsoDetailDataSet.getAllChangedRecords(); command.setParameter("FmisFsoDetailRecords", FmisFsoDetailRecords); command.setParameter("FmisFsoRecord", FmisFsoRecord); command.execute("save"); if (!command.error){ FmisFsoDetailDataSet.commitChanges(); FmisFsoDataSet.getCurrent().state = L5.model.Record.STATE_MODIFIED; L5.Msg.alert('提示','保存成功!',function(){ returnClick(); }) }else{ L5.Msg.alert('提示',"提交时出现错误!"+command.error); } } /** *事件说明:关闭按钮 **/ function returnClick(){ window.returnValue = "refresh"; window.close(); } //构造按钮 function createButton(str1,str2,record){ if(record){ return "<input type=\"button\" name=\"edit\" onclick='L5.grid.ColumnModel.onEditClick(this)' value=\"删除\"/>"; } } /** *事件说明:删除附件按钮 **/ function removeFmisFsoDetail() { var editGrid=L5.getCmp('FmisFsoDetailEditGridPanel'); var selected = editGrid.getSelectionModel().getSelections(); if(selected.length<1){ L5.Msg.alert('提示',"请选择要删除的记录!"); return false; } L5.MessageBox.confirm('确定', '确定要删除选中的记录吗?',function(state){ if(state=="yes"){ var command=new L5.Command("com.snpit.top.oa.fmis.fso.cmd.FmisFsoDetailCommand"); for(var i=0;i<selected.length;i++){ var delId=selected[i].get("fmisFsoDtlid"); command.setParameter("delId", delId); command.execute("delete"); FmisFsoDetailDataSet.remove(selected[i]); } }else{ return false; } }); } function browse(){ document.all.remark.value=BrowseFolder(); } function viewfiles(){ var textHtml=""; var folderpath=document.all.remark.value; textarea.innerHTML=traverse(folderpath,textHtml) +"共遍历文件数:"+countfiles+"<br/>"+"共遍历文件夹数:"+countfolders; } /** *事件说明:下载附件按钮 **/ function downloadFmisFsoDetail(){ }
selectFile.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <% String basePath = request.getContextPath(); String uploadUrl = basePath+"/FileUploadServlet.htm"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <link href="<%=basePath%>/jsp/com/sdepci/ucp/ftp/css/default.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="<%=basePath%>/jsp/com/sdepci/ucp/ftp/css/button.css" type="text/css" /> <script type="text/javascript" src="<%=basePath%>/jsp/com/sdepci/ucp/ftp/js/swfupload.js"></script> <script type="text/javascript" src="<%=basePath%>/jsp/com/sdepci/ucp/ftp/js/handlers.js"></script> <script type="text/javascript"> var swfu; window.onload = function () { swfu = new SWFUpload({ upload_url: "<%=uploadUrl.toString()%>", post_params: {"name" : "huliang"}, // File Upload Settings file_size_limit : "10 MB",// 1000MB file_types : "*.*", file_types_description : "所有文件", file_upload_limit : "0", file_queue_error_handler : fileQueueError, file_dialog_complete_handler : fileDialogComplete,//选择好文件后提交 file_queued_handler : fileQueued, upload_progress_handler : uploadProgress, upload_error_handler : uploadError, upload_success_handler : uploadSuccess, upload_complete_handler : uploadComplete, // Button Settings button_image_url : "<%=basePath%>/jsp/com/sdepci/ucp/ftp/images/SmallSpyGlassWithTransperancy_17x18.png", button_placeholder_id : "spanButtonPlaceholder", button_width: 180, button_height: 18, button_text : '<span class="button">选择图片 <span class="buttonSmall">(10 MB Max)</span></span>', button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }', button_text_top_padding: 0, button_text_left_padding: 18, button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT, button_cursor: SWFUpload.CURSOR.HAND, // Flash Settings flash_url : "<%=basePath%>/jsp/com/sdepci/ucp/ftp/js/swfupload.swf", custom_settings : { upload_target : "divFileProgressContainer" }, // Debug Settings debug: false //是否显示调试窗口 }); }; function startUploadFile(){ swfu.startUpload(); } function selectdiy() { new SWFUpload("setting.button_action","SELECT_FILES"); } </script> </head> <body style="padding: 2px;"> <div id="content"> <form> <div style="display: inline; border: solid 1px #7FAAFF; background-color: #C5D9FF; padding: 2px;"> <span id="spanButtonPlaceholder"></span> <input id="btnUpload" type="button" value="上 传" onclick="startUploadFile();" class="btn3_mouseout" onMouseUp="this.className='btn3_mouseup'" onmousedown="this.className='btn3_mousedown'" onMouseOver="this.className='btn3_mouseover'" onmouseout="this.className='btn3_mouseout'"/> <input id="btnCancel" type="button" value="取消所有上传" onclick="cancelUpload();" disabled="disabled" class="btn3_mouseout" onMouseUp="this.className='btn3_mouseup'" onmousedown="this.className='btn3_mousedown'" onMouseOver="this.className='btn3_mouseover'" onmouseout="this.className='btn3_mouseout'"/> </div> </form> <div id="divFileProgressContainer"></div> <div id="thumbnails"> <table id="infoTable" border="1" width="530" style="display: inline; border: solid 1px #7FAAFF; background-color: #C5D9FF; padding: 2px;margin-top:8px;"> </table> </div> </div> </html>
FmisFsoCommand.java
package com.snpit.top.oa.fmis.fso.cmd; import java.util.*; import org.loushang.next.dao.*; import org.loushang.next.data.*; import org.loushang.next.web.cmd.*; import org.loushang.sca.*; import com.snpit.top.oa.fmis.fileSequenceNumberDao; import com.snpit.top.oa.fmis.fso.dao.FmisFso; import com.snpit.top.oa.fmis.fso.dao.FmisFsoDao; import com.snpit.top.oa.fmis.fso.dao.FmisFsoDetail; import com.snpit.top.oa.fmis.fso.dao.FmisFsoDetailDao; import com.snpit.top.oa.fmis.fso.dao.IFmisFsoDomain; import com.snpit.top.oa.renli.seniortitle.dao.RlBaseSeniorTitle; /** * @title:FmisFsoSaveCommand * @description: * @author: * @since:2012-08-22 * @version:1.0 */ public class FmisFsoCommand extends BaseAjaxCommand { FmisFsoDao dao = (FmisFsoDao) DaoFactory .getDao("com.snpit.top.oa.fmis.fso.dao.FmisFsoDao"); public void save() { IFmisFsoDomain service = ScaComponentFactory.getService(IFmisFsoDomain.class, "FmisFsoDomain/FmisFsoDomain"); FmisFso fmisfso = getFmisFso(); List FmisFsoDetailList = getFmisFsoDetailList(); service.saveFmisFsoDetailList(fmisfso, FmisFsoDetailList); } public void delete() { IFmisFsoDomain service = ScaComponentFactory.getService(IFmisFsoDomain.class, "FmisFsoDomain/FmisFsoDomain"); String[] delId = (String[]) getParameter("delIds"); List list = new ArrayList(); for(int i=0;i<delId.length;i++){ list.add(delId[i]); } FmisFsoDetailDao fmisfsodetailDao = null; try{ fmisfsodetailDao = new FmisFsoDetailDao(); }catch(Exception e){ } fmisfsodetailDao.batchDeleteByFmisFso(delId); service.delete(list); } //获取主键 int fileid=fileSequenceNumberDao.getInstance().getNext(); String fmisFsoId=String.valueOf(fileid); private FmisFso getFmisFso() { Record fmisfsoRecord = (Record) getParameter("FmisFsoRecord"); FmisFso fmisfso = (FmisFso)fmisfsoRecord.toBean(FmisFso.class); fmisfso.setFmisFsoId(fmisFsoId); fmisfso.setStatus("已提交"); return fmisfso; } //保存主表信息 public void saveMain() { Record fmisfsoRecord = (Record) getParameter("FmisFsoRecord"); //获取主键 int fileid=fileSequenceNumberDao.getInstance().getNext(); String fmisFsoId=String.valueOf(fileid); if(fmisfsoRecord.get("fmisFsoId").equals("") || fmisfsoRecord.get("fmisFsoId")==null){ List<FmisFso> list = new ArrayList<FmisFso>(); FmisFso fmisfso = (FmisFso)fmisfsoRecord.toBean(FmisFso.class); fmisfso.setFmisFsoId(fmisFsoId); fmisfso.setStatus("已提交"); list.add(fmisfso); dao.save(list); }else{ FmisFso fmisfso = (FmisFso)fmisfsoRecord.toBean(FmisFso.class); dao.update(fmisfso); } } private List<FmisFsoDetail> getFmisFsoDetailList() { Record[] fmisfsodetailRecords = (Record[]) getParameter("FmisFsoDetailRecords"); if (fmisfsodetailRecords == null || fmisfsodetailRecords.length == 0) { return null; } List<FmisFsoDetail> list = new ArrayList<FmisFsoDetail>(); for (int i = 0; i < fmisfsodetailRecords.length; i++) { FmisFsoDetail fmisfsodetail = (FmisFsoDetail) fmisfsodetailRecords[i].toBean(FmisFsoDetail.class); //获取主键 int fileid=fileSequenceNumberDao.getInstance().getNext(); String fmisFsoDtlid=String.valueOf(fileid); fmisfsodetail.setFmisFsoDtlid(fmisFsoDtlid); fmisfsodetail.setFmisFsoId(fmisFsoId); list.add(fmisfsodetail); } return list; } //更新流程信息 public void updateIncident(){ String fmisFsoId=(String)getParameter("fmisFsoId"); Integer incidentno=(Integer)getParameter("incidentno"); dao.updateIncident(fmisFsoId, incidentno); } //更新单据状态 public void updateState() { String fmisFsoId=(String)getParameter("fmisFsoId"); dao.updateState(fmisFsoId); } }
FmisFsoDao.java
package com.snpit.top.oa.fmis.fso.dao; import org.loushang.persistent.jdbc.datasource.DataSourceFactory; import org.loushang.next.dao.EntityDao; /** * @title:FmisFsoDao * @description: * @author: * @since:2012-08-22 * @version:1.0 */ public class FmisFsoDao extends EntityDao<FmisFso> implements IFmisFsoDao{ public FmisFsoDao() throws Exception { this.setDataSource(DataSourceFactory.defaultFactory .getDataSource("ims")); this.afterPropertiesSet(); } @Override public Class getEntityClass() { return FmisFso.class; } public void deleteStruAll() { executeUpdate("delete from FmisFso"); } //更新流程信息 public void updateIncident(String fmisFsoId,Integer incidentno) { String sql="update FMIS_FSO set FMIS_FSO.Processname='文件外发申请',FMIS_FSO.Incidentno='"+incidentno+"' where FMIS_FSO.Fmis_Fso_Id='"+fmisFsoId+"'"; this.executeUpdate(sql); } //更新单据状态 public void updateState(String fmisFsoId) { String sql="update FMIS_FSO set FMIS_FSO.STATUS='审批' where FMIS_FSO.Fmis_Fso_Id='"+fmisFsoId+"'"; this.executeUpdate(sql); } }
FileUploadServlet.java
package com.sdepci.ucp.ftp; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPReply; import com.sdepci.fileftp.uploadFiles; import java.io.RandomAccessFile; import java.io.OutputStream; public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = -7825355637448948879L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public FTPClient ftpClient = new FTPClient(); public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //实例化ftp对象 uploadFiles uploadfile = new uploadFiles(); //连接ftp try { ftpClient.connect("10.246.8.91", 21); ftpClient.setControlEncoding("GBK"); if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){ if(ftpClient.login("test", "test")){ //uploadfile.connect("10.246.8.91", 21, "test", "test"); DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置内存缓冲区,超过后写入临时文件 factory.setSizeThreshold(10240000); // 设置临时文件存储位置 String base = "d:/upload"; File file = new File(base); if(!file.exists()) file.mkdirs(); factory.setRepository(file); ServletFileUpload upload = new ServletFileUpload(factory); // 设置单个文件的最大上传值 upload.setFileSizeMax(10002400000l); // 设置整个request的最大值 upload.setSizeMax(10002400000l); upload.setHeaderEncoding("UTF-8"); try { List<?> items = upload.parseRequest(request); FileItem item = null; String fileName = null; for (int i = 0 ;i < items.size(); i++){ item = (FileItem) items.get(i); fileName = base + File.separator + item.getName(); //设置PassiveMode传输 ftpClient.enterLocalPassiveMode(); //设置以二进制流的方式传输 ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); conf.setServerLanguageCode("zh"); //设置远程目录 ftpClient.changeWorkingDirectory(new String("test")); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 保存文件 //OutputStream out = ftpClient.appendFileStream(new String("test".getBytes("GBK"),"iso-8859-1")); // 保存文件 if (!item.isFormField() && item.getName().length() > 0) { FileInputStream fileinputstream = new FileInputStream("D:\\a.txt"); java.io.InputStream is =item.getInputStream(); try{ // boolean flag = ftpClient.storeUniqueFile("D:\\文件外发\\test\\"+item.getName(),is); boolean flag = ftpClient.storeFile("test/"+item.getName(),is); System.out.println(":::::::: test/"+item.getName()); //boolean flag = ftpClient.storeFile("test/"+item.getName(),(InputStream)fileinputstream); is.close(); }catch(Exception e){ e.printStackTrace(); } // RandomAccessFile raf = new RandomAccessFile(new File(item.getName()),"rw"); // System.out.println("%%%%"+raf); // byte[] bytes = new byte[1024]; // int c; // while((c = raf.read(bytes))!= -1){ // out.write(bytes,0,c); // } // out.flush(); // raf.close(); // out.close(); // System.out.println(item.getInputStream()); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } disconnect(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** *//** * 断开与远程服务器的连接 * @throws IOException */ public void disconnect() throws IOException{ if(ftpClient.isConnected()){ ftpClient.disconnect(); } } public void uploadFile() { //实例化ftp对象 uploadFiles uploadfile = new uploadFiles(); //连接ftp try { ftpClient.connect("10.246.8.91", 21); ftpClient.setControlEncoding("GBK"); if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){ if(ftpClient.login("test", "test")){ //设置PassiveMode传输 ftpClient.enterLocalPassiveMode(); //设置以二进制流的方式传输 ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); conf.setServerLanguageCode("zh"); //设置远程目录 ftpClient.changeWorkingDirectory(new String("test")); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 保存文件 //OutputStream out = ftpClient.appendFileStream(new String("test".getBytes("GBK"),"iso-8859-1")); // 保存文件 FileInputStream fileinputstream = new FileInputStream("D:\\a.txt"); try{ boolean flag = ftpClient.storeFile("test/a.txt",(InputStream)fileinputstream);; }catch(Exception e){ e.printStackTrace(); } } } }catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { FileUploadServlet fileservlet = new FileUploadServlet(); fileservlet.uploadFile(); } }
uploadFiles.java
package com.sdepci.fileftp; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.RandomAccessFile; import org.apache.commons.net.PrintCommandListener; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import com.sdepci.fileftp.data.DownloadStatus; import com.sdepci.fileftp.data.UploadStatus; /** *//** * 支持断点续传的FTP实用类 * @author BenZhou http://www.bt285.cn * @version 0.1 实现基本断点上传下载 * @version 0.2 实现上传下载进度汇报 * @version 0.3 实现中文目录创建及中文文件创建,添加对于中文的支持 */ public class uploadFiles { public FTPClient ftpClient = new FTPClient(); public uploadFiles(){ //设置将过程中使用到的命令输出到控制台 this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); } /** *//** * 连接到FTP服务器 * @param hostname 主机名 * @param port 端口 * @param username 用户名 * @param password 密码 * @return 是否连接成功 * @throws IOException */ public boolean connect(String hostname,int port,String username,String password) throws IOException{ ftpClient.connect(hostname, port); ftpClient.setControlEncoding("GBK"); if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){ if(ftpClient.login(username, password)){ return true; } } disconnect(); return false; } /** *//** * 从FTP服务器上下载文件,支持断点续传,上传百分比汇报 * @param remote 远程文件路径 * @param local 本地文件路径 * @return 上传的状态 * @throws IOException */ public DownloadStatus download(String[] remotes,String local) throws IOException{ //设置被动模式 ftpClient.enterLocalPassiveMode(); //ftpClient.enterRemotePassiveMode(); //设置以二进制方式传输 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); DownloadStatus result=DownloadStatus.Download_New_Success; for(String remote:remotes){ System.out.print("名称:"+remote); if(remote.endsWith(".txt") || remote.endsWith(".rar") || remote.endsWith(".doc") || remote.endsWith(".docx") || remote.endsWith(".zip") || remote.endsWith(".jpg") || remote.endsWith(".xls")){ //检查远程文件是否存在 FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes("GBK"),"iso-8859-1")); if(files.length != 1){ System.out.println("远程文件不存在"); return DownloadStatus.Remote_File_Noexist; } long lRemoteSize = files[0].getSize(); File f = new File(local+files[0].getName()); //本地存在文件,进行断点下载 if(f.exists()){ long localSize = f.length(); //判断本地文件大小是否大于远程文件大小 if(localSize >= lRemoteSize){ System.out.println("本地文件大于远程文件,下载中止"); return DownloadStatus.Local_Bigger_Remote; } //进行断点续传,并记录状态 FileOutputStream out = new FileOutputStream(f,true); ftpClient.setRestartOffset(localSize); InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1")); byte[] bytes = new byte[1024]; long step = lRemoteSize /100; long process=localSize /step; int c; while((c = in.read(bytes))!= -1){ out.write(bytes,0,c); localSize+=c; long nowProcess = localSize /step; if(nowProcess > process){ process = nowProcess; if(process % 10 == 0) System.out.println("下载进度:"+process); // 更新文件下载进度,值存放在process变量中 } } in.close(); out.close(); } else { OutputStream out = new FileOutputStream(f); InputStream in= ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1")); byte[] bytes = new byte[1024]; long step = lRemoteSize /100; long process=0; long localSize = 0L; int c; while((c = in.read(bytes))!= -1){ out.write(bytes, 0, c); localSize+=c; long nowProcess = localSize /step; if(nowProcess > process){ process = nowProcess; if(process % 10 == 0) System.out.println("下载进度:"+process); // 更新文件下载进度,值存放在process变量中 } } in.close(); out.close(); } } else { String directory=remote; boolean flage=false; if(remote.startsWith("/") && remote.endsWith("/")){ flage=ftpClient.changeWorkingDirectory(directory); }else{ flage=ftpClient.changeWorkingDirectory(remote); } if (!flage) { ftpClient.makeDirectory(directory); ftpClient.changeWorkingDirectory(directory); } //ftpClient.changeWorkingDirectory(remote); FTPFile[] ftpfiles = ftpClient.listFiles(); if(ftpfiles.length==0){ System.out.println(remote+" is null!"); }else{ System.out.println("start for loop! filelist length:"+ftpfiles.length); for(int i=0;i<ftpfiles.length;i++){ // long lRemoteSize = ftpfiles[2].getSize(); File f = new File(local+ftpfiles[2].getName()); //本地存在文件,进行断点下载 if(f.exists()){ long localSize = f.length(); //判断本地文件大小是否大于远程文件大小 if(localSize >= lRemoteSize){ System.out.println("本地文件大于远程文件,下载中止"); return DownloadStatus.Local_Bigger_Remote; } //进行断点续传,并记录状态 FileOutputStream out = new FileOutputStream(f,true); ftpClient.setRestartOffset(localSize); InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1")); byte[] bytes = new byte[1024]; long step = lRemoteSize /100; long process=localSize /step; int c; while((c = in.read(bytes))!= -1){ out.write(bytes,0,c); localSize+=c; long nowProcess = localSize /step; if(nowProcess > process){ process = nowProcess; if(process % 10 == 0) System.out.println("下载进度:"+process); // 更新文件下载进度,值存放在process变量中 } } in.close(); out.close(); } else { OutputStream out = new FileOutputStream(f); InputStream in= ftpClient.retrieveFileStream(new String(remote.getBytes("GBK"),"iso-8859-1")); byte[] bytes = new byte[1024]; long step = lRemoteSize /100; long process=0; long localSize = 0L; int c; while((c = in.read(bytes))!= -1){ out.write(bytes, 0, c); localSize+=c; long nowProcess = localSize /step; if(nowProcess > process){ process = nowProcess; if(process % 10 == 0) System.out.println("下载进度:"+process); //更新文件下载进度,值存放在process变量中 } } in.close(); out.close(); } } } } } boolean downStatus = ftpClient.completePendingCommand(); if(downStatus){ return DownloadStatus.Download_New_Success; }else{ result = DownloadStatus.Download_New_Failed; } return result; } /** *//** * 上传文件到FTP服务器,支持断点续传 * @param local 本地文件名称,绝对路径 * @param remote 远程文件路径,使用/home/directory1/subdirectory/file.ext或是 http://www.guihua.org /subdirectory/file.ext 按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构 * @return 上传结果 * @throws IOException */ public UploadStatus upload(String[] locals,String remote) throws IOException{ //设置PassiveMode传输 ftpClient.enterLocalPassiveMode(); //设置以二进制流的方式传输 ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("GBK"); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); conf.setServerLanguageCode("zh"); //设置远程目录 ftpClient.changeWorkingDirectory(new String(remote)); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); UploadStatus result=UploadStatus.Create_Directory_Success; for(String local:locals){ String localName=local.substring(local.lastIndexOf("\\")+1); //检查远程是否存在文件 FTPFile[] files = ftpClient.listFiles(new String(localName.getBytes("GBK"),"iso-8859-1")); if(files.length == 1){ long remoteSize = files[0].getSize(); File f = new File(local); long localSize = f.length(); if(remoteSize==localSize){ return UploadStatus.File_Exits; }else if(remoteSize > localSize){ return UploadStatus.Remote_Bigger_Local; } //尝试移动文件内读取指针,实现断点续传 result = uploadFile(localName, f, ftpClient, remoteSize); //如果断点续传没有成功,则删除服务器上文件,重新上传 if(result == UploadStatus.Upload_From_Break_Failed){ if(!ftpClient.deleteFile(localName)){ return UploadStatus.Delete_Remote_Faild; } result = uploadFile(localName, f, ftpClient, 0); } }else { result = uploadFile(localName, new File(local), ftpClient, 0); } } return result; } /** *//** * 断开与远程服务器的连接 * @throws IOException */ public void disconnect() throws IOException{ if(ftpClient.isConnected()){ ftpClient.disconnect(); } } /** *//** * 递归创建远程服务器目录 * @param remote 远程服务器文件绝对路径 * @param ftpClient FTPClient对象 * @return 目录创建是否成功 * @throws IOException */ public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{ UploadStatus status = UploadStatus.Create_Directory_Success; String directory = remote.substring(0,remote.lastIndexOf("/")+1); if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes("GBK"),"iso-8859-1"))){ //如果远程目录不存在,则递归创建远程服务器目录 int start=0; int end = 0; if(directory.startsWith("/")){ start = 1; }else{ start = 0; } end = directory.indexOf("/",start); while(true){ String subDirectory = new String(remote.substring(start,end).getBytes("GBK"),"iso-8859-1"); if(!ftpClient.changeWorkingDirectory(subDirectory)){ if(ftpClient.makeDirectory(subDirectory)){ ftpClient.changeWorkingDirectory(subDirectory); }else { System.out.println("创建目录失败"); return UploadStatus.Create_Directory_Fail; } } start = end + 1; end = directory.indexOf("/",start); //检查所有目录是否创建完毕 if(end <= start){ break; } } } return status; } /** *//** * 上传文件到服务器,新上传和断点续传 * @param remoteFile 远程文件名,在上传之前已经将服务器工作目录做了改变 * @param localFile 本地文件File句柄,绝对路径 * @param processStep 需要显示的处理进度步进值 * @param ftpClient FTPClient引用 * @return * @throws IOException */ public UploadStatus uploadFile(String remoteFile,File localFile,FTPClient ftpClient,long remoteSize) throws IOException{ UploadStatus status; System.out.println("文件名称:"+remoteFile); //显示进度的上传 long step = localFile.length() / 100; long process = 0; long localreadbytes = 0L; RandomAccessFile raf = new RandomAccessFile(localFile,"rw"); OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes("GBK"),"iso-8859-1")); //断点续传 if(remoteSize>0){ ftpClient.setRestartOffset(remoteSize); process = remoteSize /step; raf.seek(remoteSize); localreadbytes = remoteSize; } byte[] bytes = new byte[1024]; int c; while((c = raf.read(bytes))!= -1){ out.write(bytes,0,c); localreadbytes+=c; if(localreadbytes / step != process){ process = localreadbytes / step; System.out.println("上传进度:" + process); //汇报上传状态 } } out.flush(); raf.close(); out.close(); boolean result =ftpClient.completePendingCommand(); if(remoteSize > 0){ status = result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed; }else { status = result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed; } return status; } /** * 删除文件 * @param remoteFilePath */ public boolean delFile(String remoteFilePath) { try { return ftpClient.deleteFile(remoteFilePath); } catch (IOException e) { e.printStackTrace(); } return false; } }
UploadStatus.java
package com.sdepci.fileftp.data; public class UploadStatus { private String name; private UploadStatus(String mn){name=mn;} public String toString(){return name;} public static final UploadStatus Create_Directory_Success=new UploadStatus("创建目录成功!"), Create_Directory_Fail=new UploadStatus("创建目录失败!"), Delete_Remote_Faild=new UploadStatus("从服务器上删除失败!"), File_Exits=new UploadStatus("文件存在!"), Remote_Bigger_Local=new UploadStatus("远程文件大于本地文件!"), Upload_From_Break_Success=new UploadStatus("断点续传下载成功!"), Upload_From_Break_Failed=new UploadStatus("断点续传下载失败!"), Upload_New_File_Success=new UploadStatus("下载成功!"), Upload_New_File_Failed=new UploadStatus("下载失败!"); }
相关推荐
一堆代码样本,用于OCPJ 8考试(1Z0-809) 该结构基于考试主题,并大致遵循@ eh3rrera的 。 在为OCPJ 8进行练习时,我写了它们来快速测试jse8。它们并不是要经过精心设计或遵循任何干净的代码规则。 只需尝试,...
在代码实现中,最小堆的常见操作包括初始化堆、插入元素、删除最小元素、查看最小元素以及堆化(将普通数组转化为堆)。这些操作的复杂度如下: - 插入元素(Insert):平均O(log n),最坏O(n) - 删除最小元素...
堆排序是一种基于比较的排序算法,它通过构造一个大顶堆或小顶堆来实现排序。在本场景中,我们关注的是堆排序的源代码,它适用于openSUSE 11.4操作系统,并且是使用GCC version 4.5.1编译器编译的。在这个名为"sort...
一个堆排序的代码,运行成功的啊。和大家分享一下啊
"代码库和一堆乱七八糟的代码"这个描述可能暗示了一个开发过程中常见的现象,即代码库中的代码组织不够有序,可能存在混乱或未整理的状态。这通常会影响代码的可读性、可维护性和团队协作效率。 首先,我们来逐一...
Verilog是一种硬件描述语言,广泛用于数字系统的建模和设计,包括寄存器堆的实现。寄存器堆是数字系统中的重要组成部分,通常在微处理器、FPGA或ASIC等设计中作为数据存储单元出现。它能存储指令、数据或其他信息,...
下面是一个基本的C++实现堆排序的示例代码: ```cpp #include #include void heapify(int arr[], int n, int i) { int largest = i; // 初始化最大元素为根节点 int left = 2 * i + 1; int right = 2 * i + 2...
•特征1:是一堆代码的集合; •特征2:一个半成品的应用; •特征3:包含了一些优秀的设计模式; 定义:框架是一堆包含了常量、方法和类等代码的集合,它是一个半成品的应用,只包含了一些项目开发的时候所使用的...
作为一个初级程序猿来说:最苦恼的莫过于“兴冲冲得搞到了一批感兴趣的代码”,结果拷贝进ECLIPSE之后,处处都是乱码,是非常悲催的事情,如果是一堆代码更是雪上加霜; 为了“一劳永逸”的解决此问题,于是写了这个...
7,然后在新弹出的对话框中,将右侧那一堆代码复制出来,粘贴到注册机的上面框中,这时注册机会在下面的框中生成新的注册激活代码。 8,复制粘贴生成的激活代码,到Enter Serial Number...弹出激活框的右侧,点击...
二叉堆是一种特殊的数据结构,它在计算机科学中扮演着重要的角色,特别是在优先队列和排序算法中。本文将深入探讨二叉堆的概念、性质、实现以及其在实际应用中的运用。 二叉堆是一个完全二叉树,可以分为两种类型:...
堆排序是一种基于比较的排序算法,利用了堆的数据结构。它将待排序数组构造成一个大顶堆(或小顶堆),此时整个数组的最大值(或最小值)就在堆顶上;然后将堆顶元素与末尾元素进行交换,此时末尾就为最大值(或...
粘贴到刚才弹出的对话框中,点击Activate,因为是断网的,系统会要求离线激活,然后在新弹出的对话框中,将右侧那一堆代码复制出来,粘贴到注册机的上面框中,这时注册机会在下面的框中生成新的注册激活代码,复制...
粘贴到刚才弹出的对话框中,点击Activate,因为是断网的,系统会要求离线激活,然后在新弹出的对话框中,将右侧那一堆代码复制出来,粘贴到注册机的上面框中,这时注册机会在下面的框中生成新的注册激活代码,复制...
很多资源下载都说什么常用算法实现,结果下载下来分类也没分,名字也没,一堆代码.都不知道到底算什么算法..相信大家一定要遇到过。我这里有一些(虽然不多)包括图的遍历啊,关键路径,二叉树.迪杰斯特拉等等算法的C实现....
7,然后在新弹出的对话框中,将右侧那一堆代码复制出来,粘贴到注册机的上面框中,这时注册机会在下面的框中生成新的注册激活代码。 8,复制粘贴生成的激活代码,到Enter Serial Number...弹出激活框的右侧,点击...
7、然后在新弹出的对话框中,将右侧那一堆代码复制出来,粘贴到注册机的上面框中,这时注册机会在下面的框中生成新的注册激活代码。 8、复制粘贴生成的激活代码,到Enter Serial Number...弹出激活框的右侧,点击...
在计算机科学中,堆通常指的是一种完全二叉树结构,其每个节点的值都大于等于(最大堆)或小于等于(最小堆)其子节点的值。 #### 二、堆排序基本概念 1. **完全二叉树**: 完全二叉树是指除了最后一层外每一层都是...
在《算法导论》一书中,二项堆被详细地讲解并提供了源代码实现。以下是对二项堆及相关操作的详细解释: 1. **二项堆的定义**: 二项堆是由若干棵二项树(每个节点最多两个子节点)组成的集合,这些树满足以下两个...
下面是一个简化的C++堆排序代码示例: ```cpp #include #include void heapify(int arr[], int n, int i) { int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left [left] > arr...