@Value('${ftp.hostname}') String hostname @Value('${ftp.port}') int port @Value('${ftp.httpPort}') int httpPort @Value('${ftp.username}') String username @Value('${ftp.password}') String password @Value('${ftp.pathname}') String pathname //指定上传文件服务器路径
/** * 获得ftp文件服务器连接 * */ def connect(){ FTPClient ftp = new FTPClient(); ftp.setControlEncoding("UTF-8"); int reply; ftp.connect(hostname,port); //登录 ftp.login(username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); } //指定目录 ftp.changeWorkingDirectory(pathname) return ftp; }
def uploadAvatar(Attachment attachment) { def file = request.getFile("file") if (file.empty) { flash.message = message(code: '请选择要上传的文件') respond attachment, model: [targetUri: params['targetUri']], view: 'create' return } def imageExtensionsList = ['jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG'] def fileExtensionsList = ['pdf', 'doc', 'docx', 'xlsx', 'xls'] def videoExtensionsList = ['mov', 'mp4', 'avi', 'rm', '3gp', 'mkv', 'wmv', 'ogg', 'rmvb'] def audioExtensionsList = ['mp3', 'wav', 'amr', 'mid','m4a']
//上传文件名称 def fileOrgName = file?.getOriginalFilename() def fileType = fileOrgName?.split('\\.')[-1] fileType = fileType?.toLowerCase() if (!(fileType in imageExtensionsList) && !(fileType in fileExtensionsList) && !(fileType in videoExtensionsList) && !(fileType in audioExtensionsList)) { flash.message = message(code: '文件格式不支持') respond attachment, model: [targetUri: params['targetUri']], view: 'create' return }
//文件上传到本地本地路径,再从本地拿文件上传到ftp服务器 (获取不到系统文件路径,所以先上传的本地,从本地再上传ftp ,然后删除本地 文件) def code = UUID.randomUUID().toString() File fileImage = new File(servletContext.getRealPath("/"), "images/${code}.${fileType}") file.transferTo(fileImage)
if (fileImage) { //文件保存按照 上传文件名称保存 attachment.fileName = fileOrgName attachment.fileUrl = "http://"+hostname+":"+httpPort+"/${code}.${fileType}" boolean result = false InputStream fis = null FTPClient ftp = connect() // FTPClientConfig conf=new FTPClientConfig(FTPClientConfig.SYST_NT); // conf.setServerLanguageCode("zh"); // ftp.configure(conf); try { ftp.setFileType(FTP.BINARY_FILE_TYPE) //使用二进制流上传文件 fis = new FileInputStream(fileImage) ftp.setControlEncoding("UTF-8") ftp.enterLocalPassiveMode() // ftp.enterLocalActiveMode() ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE) result = ftp.storeFile("${code}.${fileType}", fis); ftp.logout(); }catch(Exception e){ e.printStackTrace() }finally{ fis.close() if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { ioe.printStackTrace() } } // 删除临时文件 if (fileImage.isFile() && fileImage.exists()) { def flag = fileImage.delete() System.out.print(flag) } } } }
}