java下載ftp伺服器端檔案直接開啟
阿新 • • 發佈:2019-01-22
畢業後的第一份工作,
到手的第一個任務是 從ftp伺服器端下載檔案,並直接呼叫系統預設程式開啟
直接貼上Controller程式碼
<span style="white-space:pre"> </span>@RequestMapping("/downloadZj") @ResponseBody public Map<String,String> downloadZj(long sn, short xh) throws SocketException, IOException { Map<String,String> result = new HashMap<String,String>(); Map<String, Object> map = zjzsService.getPath(sn, xh); if(map==null||map.size()==0){ result.put("success", "false"); result.put("msg", "該證據不存在"); return result; } String serverName = (String) map.get("SERVERNAME"); int port = Integer.parseInt(map.get("PORT").toString()); String userName = (String) map.get("USERNAME"); String pwd = (String) map.get("PWD"); String serverFile = (String) map.get("FUXDPATH") + "/" + map.get("ZIXDPATH") + "/" + map.get("WJMC"); FTPClient ftp = new FTPClient(); ftp.connect(serverName, port); // 也可以採用預設埠直接連線FTP伺服器 // ftp.connect(serverName); int reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (ftp.login(userName, pwd)) { zjzsService.recodelog("登入ftp伺服器"); } } //下載檔案到本地 File localFile = new File("E:\\" + (String) map.get("WJMC")); OutputStream out = new FileOutputStream(localFile); ftp.retrieveFile(serverFile, out); // 開啟本地檔案 Desktop.getDesktop().open(localFile); result.put("success", "true"); result.put("msg", ""); out.close(); ftp.logout(); if (ftp.isConnected()) { ftp.disconnect(); } return result; }