ftp 檔案上傳與刪除
阿新 • • 發佈:2019-02-13
/** * 初始化ftp伺服器 */ private FTPClient initFtpClient() throws Exception { String host = FamousClassRoomPropertiesConfig.getZjeduFileUploadHost(); int port = FamousClassRoomPropertiesConfig.getZjeduFileUploadPort(); String userName = FamousClassRoomPropertiesConfig.getZjeduFileUploadUsername(); String passworld = FamousClassRoomPropertiesConfig.getZjeduFileUploadPassword(); FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("utf-8"); //連線ftp伺服器 ftpClient.connect(host, port); //登入ftp伺服器 ftpClient.login(userName, passworld); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { ftpClient.disconnect(); throw new Exception("連線伺服器失敗"); } return ftpClient; }
檔案上傳:
/** * * @param folder 上傳的資料夾 * @param fileName 檔名稱 * @param inputStream * @return * @throws Exception */ public String fileUpload(String folder, String fileName, InputStream inputStream) throws Exception { FTPClient ftpClient = null; try { ftpClient = initFtpClient(); Long time = System.currentTimeMillis(); ftpClient.changeWorkingDirectory(folder); ftpClient.storeFile(fileName, inputStream); LOGGER.warn("檔案上傳時間:" + (System.currentTimeMillis() - time)); return ZJEDU_PATH + folder + "/" + fileName; } catch (Exception e) { throw new Exception("檔案上傳失敗", e); } finally { if (inputStream != null) { inputStream.close(); } if (ftpClient != null) { ftpClient.disconnect(); } } }
刪除檔案:
/** * ftp刪除檔案 * @param folder 資料夾名稱 * @param fileNames 檔名列表 * @return * @throws Exception */ public boolean deleteZjeduFile(String folder, List<String> fileNames) throws Exception{ FTPClient ftpClient = null; boolean flag = false; try{ ftpClient = initFtpClient(); ftpClient.changeWorkingDirectory(folder); for(String fileName : fileNames) { flag = ftpClient.deleteFile(fileName); } return flag; }catch (Exception e){ throw e; }finally { if (ftpClient != null) { ftpClient.disconnect(); } } }