配置
ftp: server: 192.168.1.000 port: 21 userName: administrator userPassword:
ftpmodel 实体类
@Component public class FtpModel { @Value("${ftp.server}") private String server; @Value("${ftp.port}") private int port; @Value("${ftp.userName}") private String userName; @Value("${ftp.userPassword}") private String userPassword; public String getServer() { return server; } public void setServer(String server) { this.server = server; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } @Override public String toString() { return "FtpModel{" + "server='" + server + '\'' + ", port=" + port + ", userName='" + userName + '\'' + ", userPassword='" + userPassword + '\'' + '}'; } }
操作类
SpringUtils 》》》 SpringUtils
public class FtpUtils { private final Logger logger = LoggerFactory.getLogger(FtpUtils.class); private String server; private int port; private String userName; private String userPassword; private String photoAllowSuffix = "jpg,png,gif,jpeg,bmp";//图片允许文件格式 public static List<String> arFiles; private static FtpModel ftpModel = (FtpModel) SpringUtils.getBeanByClass(FtpModel.class); private FTPClient ftpClient = null; public FtpUtils(String server, int port, String userName, String userPassword) { this.server = server; this.port = port; this.userName = userName; this.userPassword = userPassword; } /*public FtpUtils(FtpModel ftpModel) { this.server = ftpModel.getServer(); this.port = ftpModel.getPort(); this.userName = ftpModel.getUserName(); this.userPassword = ftpModel.getUserPassword(); }*/ public FtpUtils() { this.server = ftpModel.getServer(); this.port = ftpModel.getPort(); this.userName = ftpModel.getUserName(); this.userPassword = ftpModel.getUserPassword(); } /** * 单图片上传 * @param file * @param destDir * @throws IOException */ public String uploadsPhoto(MultipartFile file, String destDir) throws IOException { String fileName = ""; //文件后缀名 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); int length = getPhotoAllowSuffix().indexOf(suffix.toLowerCase());//转成小写比较 //符合条件 if (length >= 0){ if (openStatic()){ String fileFolder = getFileFolder(); String fileNameNew =getFileNameNew()+"."+suffix; if (upload(file.getInputStream(),fileNameNew,"/"+destDir+"/"+fileFolder)){ //新文件名 fileName = "/"+destDir+"/"+fileFolder+"/"+fileNameNew; } closeStatic(); } } return fileName; } /** * 多图片上传 * @param files * @param destDir * @return * @throws IOException */ public List<String> uploadsPhoto(MultipartFile[] files, String destDir) throws IOException { List<String> fileNames = new ArrayList<>(); if (files.length > 0){ try { if (openStatic()) { for (MultipartFile file:files){ //文件后缀名 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); int length = getPhotoAllowSuffix().indexOf(suffix.toLowerCase());//转成小写比较 //符合条件 if (length >= 0){ String fileFolder = getFileFolder(); String fileNameNew =getFileNameNew()+"."+suffix; if (upload(file.getInputStream(),fileNameNew,"/"+destDir+"/"+fileFolder)){ //新文件名 fileNames.add(String.format("/%s/%s/%s",destDir,fileFolder,fileNameNew)); } } } } } catch (IOException e) { e.printStackTrace(); } finally { closeStatic(); } } return fileNames; } /** * 查看图片流 * @param response * @param path */ public void showPhoto(HttpServletResponse response, String path){ if (openStatic()){ getPhoto(response,path); closeStatic(); } } /** * 上传图片 返回文件对象 * @param file * @param destDir * @return * @throws IOException */ public FileModel uploadsPhotoReturnModel(MultipartFile file, String destDir) throws IOException { FileModel fileModel = new FileModel(); //文件后缀名 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); int length = getPhotoAllowSuffix().indexOf(suffix.toLowerCase());//转成小写比较 //符合条件 if (length >= 0){ if (openStatic()){ String fileFolder = getFileFolder(); String fileNameNew =getFileNameNew()+"."+suffix; if (upload(file.getInputStream(),fileNameNew,"/"+destDir+"/"+fileFolder)){ fileModel = new FileModel(file.getOriginalFilename(),destDir+"/"+fileFolder+"/"+fileNameNew,file.getSize(),file.getContentType(),suffix); } closeStatic(); } } return fileModel; } public List<FileModel> uploadsPhotoReturnModel(MultipartFile[] files, String destDir) throws IOException { List<FileModel> fileModels = new ArrayList<>(); if (files.length > 0){ try { if (openStatic()){ for (MultipartFile file : files){ //文件后缀名 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); int length = getPhotoAllowSuffix().indexOf(suffix.toLowerCase());//转成小写比较 //符合条件 if (length >= 0){ String fileFolder = getFileFolder(); String fileNameNew =getFileNameNew()+"."+suffix; if (upload(file.getInputStream(),fileNameNew,"/"+destDir+"/"+fileFolder)){ fileModels.add(new FileModel(file.getOriginalFilename(),destDir+"/"+fileFolder+"/"+fileNameNew,file.getSize(),file.getContentType(),suffix)); } } } } } catch (IOException e) { e.printStackTrace(); } finally { closeStatic(); } } return fileModels; } public FileModel uploadsFileReturnModel(MultipartFile file, String destDir) throws IOException { FileModel fileModel = new FileModel(); //文件后缀名 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); if (openStatic()){ String fileFolder = getFileFolder(); String fileNameNew =getFileNameNew()+"."+suffix; if (upload(file.getInputStream(),fileNameNew,"/"+destDir+"/"+fileFolder)){ fileModel = new FileModel(file.getOriginalFilename(),destDir+"/"+fileFolder+"/"+fileNameNew,file.getSize(),file.getContentType(),suffix); } closeStatic(); } return fileModel; } public String uploadsFile(MultipartFile file, String destDir) throws IOException { String fileName = ""; //文件后缀名 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); if (openStatic()){ String fileFolder = getFileFolder(); String fileNameNew =getFileNameNew()+"."+suffix; if (upload(file.getInputStream(),fileNameNew,"/"+destDir+"/"+fileFolder)){ fileName = "/"+destDir+"/"+fileFolder+"/"+fileNameNew; } closeStatic(); } return fileName; } public String uploadsFile(File file, String destDir) throws IOException { String fileName = ""; InputStream is =new FileInputStream(file); //文件后缀名 String suffix = file.getName().substring(file.getName().lastIndexOf(".")+1); if (openStatic()){ String fileFolder = getFileFolder(); String fileNameNew =getFileNameNew()+"."+suffix; if (upload(is,fileNameNew,"/"+destDir+"/"+fileFolder)){ fileName = "/"+destDir+"/"+fileFolder+"/"+fileNameNew; } closeStatic(); } return fileName; } public String uploadsUeFile(File file, String destDir) throws IOException { String fileName = ""; InputStream is =new FileInputStream(file); //文件后缀名 String suffix = file.getName().substring(file.getName().lastIndexOf(".")+1); if (openStatic()){ String fileNameNew =getFileNameNew()+"."+suffix; if (upload(is,fileNameNew,destDir)){ fileName = destDir+fileNameNew; } closeStatic(); } return fileName; } public List<FileModel> uploadsFileReturnModel(MultipartFile[] files, String destDir) throws IOException { List<FileModel> fileModels = new ArrayList<>(); if (files.length > 0){ try { if (openStatic()){ for (MultipartFile file : files){ //文件后缀名 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); String fileFolder = getFileFolder(); String fileNameNew =getFileNameNew()+"."+suffix; if (upload(file.getInputStream(),fileNameNew,"/"+destDir+"/"+fileFolder)){ fileModels.add(new FileModel(file.getOriginalFilename(),destDir+"/"+fileFolder+"/"+fileNameNew,file.getSize(),file.getContentType(),suffix)); } } } } catch (IOException e) { e.printStackTrace(); } finally { closeStatic(); } } return fileModels; } /** * 下载 * @param response * @param filename * @param path */ public void downloadFile(HttpServletResponse response, String filename, String path){ if (openStatic()){ get(response, filename,path); closeStatic(); } } /** * 连接服务器 * @return 连接成功与否 true:成功, false:失败 */ public boolean open() { if (ftpClient != null && ftpClient.isConnected()) { return true; } try { ftpClient = new FTPClient(); // 连接 ftpClient.connect(this.server, this.port); ftpClient.login(this.userName, this.userPassword); setFtpClient(ftpClient); // 检测连接是否成功 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.close(); System.err.println("FTP server refused connection."); System.exit(1); } System.out.println("open FTP success:" + this.server + ";port:" + this.port + ";name:" + this.userName + ";pwd:" + this.userPassword); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置上传模式.binally or ascii return true; } catch (Exception ex) { this.close(); ex.printStackTrace(); return false; } } /** * 连接服务器 * @return 连接成功与否 true:成功, false:失败 */ public boolean openStatic() { if (ftpClient != null && ftpClient.isConnected()) { return true; } try { ftpClient = new FTPClient(); // 连接 ftpClient.connect(this.getServer(), this.getPort()); ftpClient.login(this.getUserName(), this.getUserPassword()); setFtpClient(ftpClient); // 检测连接是否成功 int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.close(); System.err.println("FTP server refused connection."); System.exit(1); } logger.info("成功打开 FTP ip:{};port:{};name:{};pwd:{}", this.getServer(),this.getPort(),this.getUserName(),this.getUserPassword()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置上传模式.binally or ascii return true; } catch (Exception ex) { this.close(); ex.printStackTrace(); return false; } } /** * 切换到父目录 * @return 切换结果 true:成功, false:失败 */ private boolean changeToParentDir() { try { return ftpClient.changeToParentDirectory(); } catch (IOException e) { e.printStackTrace(); return false; } } /** * 改变当前目录到指定目录 * @param dir 目的目录 * @return 切换结果 true:成功,false:失败 */ private boolean cd(String dir) { try { return ftpClient.changeWorkingDirectory(dir); } catch (IOException e) { e.printStackTrace(); return false; } } /** * 获取目录下所有的文件名称 * * @param filePath 指定的目录 * @return 文件列表,或者null */ private FTPFile[] getFileList(String filePath) { try { return ftpClient.listFiles(filePath); } catch (IOException e) { e.printStackTrace(); return null; } } /** * 层层切换工作目录 * @param ftpPath 目的目录 * @return 切换结果 */ public boolean changeDir(String ftpPath) { if (!ftpClient.isConnected()) { return false; } try { //进入根目录 ftpClient.changeWorkingDirectory("/"); // 将路径中的斜杠统一 char[] chars = ftpPath.toCharArray(); StringBuffer sbStr = new StringBuffer(256); for (int i = 0; i < chars.length; i++) { if ('\\' == chars[i]) { sbStr.append('/'); } else { sbStr.append(chars[i]); } } ftpPath = sbStr.toString(); if (ftpPath.indexOf('/') == -1) { // 只有一层目录 ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1")); } else { // 多层目录循环创建 String[] paths = ftpPath.split("/"); for (int i = 0; i < paths.length; i++) { ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1")); } } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 循环创建目录,并且创建完目录后,设置工作目录为当前创建的目录下 * @param ftpPath 需要创建的目录 * @return */ public boolean mkDir(String ftpPath) { if (!ftpClient.isConnected()) { return false; } try { //进入根目录 ftpClient.changeWorkingDirectory("/"); // 将路径中的斜杠统一 char[] chars = ftpPath.toCharArray(); StringBuffer sbStr = new StringBuffer(256); for (int i = 0; i < chars.length; i++) { if ('\\' == chars[i]) { sbStr.append('/'); } else { sbStr.append(chars[i]); } } ftpPath = sbStr.toString(); //System.out.println("ftpPath:" + ftpPath); if (ftpPath.indexOf('/') == -1) { // 只有一层目录 ftpClient.makeDirectory(new String(ftpPath.getBytes(), "iso-8859-1")); ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "iso-8859-1")); } else { // 多层目录循环创建 String[] paths = ftpPath.split("/"); for (int i = 0; i < paths.length; i++) { ftpClient.makeDirectory(new String(paths[i].getBytes(), "iso-8859-1")); ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "iso-8859-1")); } } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 上传文件到FTP服务器 * @param localDirectoryAndFileName 本地文件目录和文件名 * @param ftpFileName 上传到服务器的文件名 * @param ftpDirectory FTP目录如:/path1/pathb2/,如果目录不存在会自动创建目录 * @return */ public boolean upload(String localDirectoryAndFileName, String ftpFileName, String ftpDirectory) { if (!ftpClient.isConnected()) { return false; } boolean flag = false; if (ftpClient != null) { File srcFile = new File(localDirectoryAndFileName); FileInputStream fis = null; try { fis = new FileInputStream(srcFile); // 创建目录 this.mkDir(ftpDirectory); ftpClient.setBufferSize(100000); ftpClient.setControlEncoding("UTF-8"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 上传 flag = ftpClient.storeFile(new String(ftpFileName.getBytes(), "iso-8859-1"), fis); } catch (Exception e) { this.close(); e.printStackTrace(); return false; } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("上传文件成功,本地文件名: " + localDirectoryAndFileName + ",上传到目录:" + ftpDirectory + "/" + ftpFileName); return flag; } public boolean rename(String localDirectoryAndFileName, String ftpFileName, String ftpDirectory) { if (!ftpClient.isConnected()) { return false; } boolean flag = false; if (ftpClient != null) { File srcFile = new File(localDirectoryAndFileName); FileInputStream fis = null; try { fis = new FileInputStream(srcFile); // 创建目录 this.mkDir(ftpDirectory); ftpClient.setBufferSize(100000); ftpClient.setControlEncoding("UTF-8"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // 上传 flag = ftpClient.storeFile(new String(ftpFileName.getBytes(), "iso-8859-1"), fis); } catch (Exception e) { this.close(); e.printStackTrace(); return false; } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("上传文件成功,本地文件名: " + localDirectoryAndFileName + ",上传到目录:" + ftpDirectory + "/" + ftpFileName); return flag; } public boolean upload(InputStream inputStream, String ftpFileName, String ftpDirectory) { if (!ftpClient.isConnected()) { return false; } boolean flag = false; if (ftpClient != null) { try { // 创建目录 this.mkDir(ftpDirectory); ftpClient.setBufferSize(100000); ftpClient.setControlEncoding("UTF-8"); // 设置文件类型(二进制) ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); String fileName = new String(ftpFileName.getBytes(), "iso-8859-1"); // 上传 flag = ftpClient.storeFile(fileName, inputStream); logger.info("成功上传 路径:{}/{}",ftpDirectory,fileName); } catch (Exception e) { this.close(); e.printStackTrace(); return false; } finally { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } //System.out.println("上传文件成功,本地文件名: " + ftpFileName + ",上传到目录:" + ftpDirectory + "/" + ftpFileName); return flag; } /** * 从FTP服务器上下载文件 * @param ftpDirectoryAndFileName ftp服务器文件路径,以/dir形式开始 * @param localDirectoryAndFileName 保存到本地的目录 * @return */ public boolean get(String ftpDirectoryAndFileName, String localDirectoryAndFileName) { if (!ftpClient.isConnected()) { return false; } ftpClient.enterLocalPassiveMode(); // Use passive mode as default try { // 将路径中的斜杠统一 char[] chars = ftpDirectoryAndFileName.toCharArray(); StringBuffer sbStr = new StringBuffer(256); for (int i = 0; i < chars.length; i++) { if ('\\' == chars[i]) { sbStr.append('/'); } else { sbStr.append(chars[i]); } } ftpDirectoryAndFileName = sbStr.toString(); String filePath = ftpDirectoryAndFileName.substring(0, ftpDirectoryAndFileName.lastIndexOf("/")); String fileName = ftpDirectoryAndFileName.substring(ftpDirectoryAndFileName.lastIndexOf("/") + 1); this.changeDir(filePath); ftpClient.retrieveFile(new String(fileName.getBytes(), "iso-8859-1"), new FileOutputStream(localDirectoryAndFileName)); // download // file System.out.println(ftpClient.getReplyString()); // check result System.out.println("从ftp服务器上下载文件:" + ftpDirectoryAndFileName + ", 保存到:" + localDirectoryAndFileName); return true; } catch (IOException e) { e.printStackTrace(); return false; } } /** * 下载文件 * @param response * @param fileName 文件名称 安宁市第一小学.jpg * @param path ftp文件路径 /user/2017-12-29/20171229121635651.jpg * @return */ public boolean get(HttpServletResponse response, String fileName, String path) { response.setCharacterEncoding("UTF-8"); response.setContentType("multipart/form-data;charset=UTF-8"); if (!ftpClient.isConnected()) { return false; } ftpClient.enterLocalPassiveMode(); // Use passive mode as default try { this.changeDir(path); String fileName2 = path.substring(path.lastIndexOf("/") + 1); response.setHeader("Content-Disposition", "attachment;fileName="+ new String( fileName.getBytes("gb2312"), "ISO8859-1" ) ); OutputStream os = response.getOutputStream(); ftpClient.retrieveFile(fileName2, os); os.flush(); os.close(); // file System.out.println(ftpClient.getReplyString()); // check result System.out.println("从ftp服务器上下载文件:" + fileName); return true; } catch (IOException e) { e.printStackTrace(); return false; } } /** * 获取图片 * @param response * @param path * @return */ public boolean getPhoto(HttpServletResponse response, String path) { if (!ftpClient.isConnected()) { return false; } ftpClient.enterLocalPassiveMode(); // Use passive mode as default InputStream in = null; try { this.changeDir(path); String fileName = path.substring(path.lastIndexOf("/") + 1); //OutputStream os = response.getOutputStream(); //ftpClient.retrieveFile(fileName, os); //in = ftpClient.retrieveFileStream(fileName); in = ftpClient.retrieveFileStream(new String(fileName.getBytes("UTF-8"), "ISO-8859-1")); OutputStream out=response.getOutputStream(); //ftpClient.retrieveFile(); byte[] len= new byte[1024*2]; int read = 0; while((read=in.read(len)) != -1){ out.write(len, 0, read); } out.flush(); out.close(); in.close(); ftpClient.completePendingCommand(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } public FTPFile[] getFileNameLists(String path) { FTPFile[] strings ={}; if (openStatic()){ this.changeDir(path); strings = getFileNameLists(path); closeStatic(); } return strings; } /** * 返回FTP目录下的文件列表 * @param pathName * @return */ public String[] getFileNameList(String pathName) { try { return ftpClient.listNames(pathName); } catch (IOException e) { e.printStackTrace(); return null; } } /** * 删除FTP上的文件 * @param ftpDirAndFileName 路径开头不能加/,比如应该是test/filename1 * @return */ public boolean deleteFile(String ftpDirAndFileName) { if (!ftpClient.isConnected()) { return false; } try { return ftpClient.deleteFile(ftpDirAndFileName); } catch (IOException e) { e.printStackTrace(); return false; } } /** * 删除FTP目录 * @param ftpDirectory * @return */ public boolean deleteDirectory(String ftpDirectory) { if (!ftpClient.isConnected()) { return false; } try { return ftpClient.removeDirectory(ftpDirectory); } catch (IOException e) { e.printStackTrace(); return false; } } public List getFileListNext(String path) throws IOException { arFiles = new ArrayList<>(); if (openStatic()){ List(path); closeStatic(); } return arFiles; } /** * 递归遍历出目录下面所有文件 * * @param pathName 需要遍历的目录,必须以"/"开始和结束 * @throws IOException */ public void List(String pathName) throws IOException { if (pathName.startsWith("/") && pathName.endsWith("/")) { //更换目录到当前目录 ftpClient.changeWorkingDirectory(pathName); FTPFile[] files = ftpClient.listFiles(); for (FTPFile file : files) { if (file.isFile()) { arFiles.add(pathName + file.getName()); } else if (file.isDirectory()) { String suffix = file.getName().substring(file.getName().lastIndexOf(".")+1); // 需要加此判断。否则,ftp默认将‘项目文件所在目录之下的目录(./)’与‘项目文件所在目录向上一级目录下的目录(../)’都纳入递归,这样下去就陷入一个死循环了。需将其过滤掉。 if (!".".equals(file.getName()) && !"..".equals(file.getName())) { List(pathName + file.getName() + "/"); } } } } } /** * 关闭链接 */ public void close() { try { if (ftpClient != null && ftpClient.isConnected()) { ftpClient.disconnect(); } logger.info("成功关闭连接,服务器ip:{},端口:{}",this.getServer(),this.getPort()); } catch (Exception e) { e.printStackTrace(); } } public void closeStatic() { try { if (ftpClient != null && ftpClient.isConnected()) { ftpClient.disconnect(); } logger.info("成功关闭连接,服务器ip:{},端口:{}",this.getServer(),this.getPort()); } catch (Exception e) { e.printStackTrace(); } } public FTPClient getFtpClient() { return ftpClient; } public void setFtpClient(FTPClient ftpClient) { this.ftpClient = ftpClient; } public static void main(String[] args) { FtpUtils f = new FtpUtils("192.168.x.xxx", 21, "username", "password"); try { if(f.open()) { String fileName = "bljh.sql"; //上传 //f.upload("e:/bljh.sql", fileName, "test1"); //遍历 /*FTPFile[] list = f.getFileList("test1"); for(FTPFile file : list) { String name = file.getName(); System.out.println("--" + new String(name.getBytes("iso-8859-1"), "GB2312")); }*/ //f.List("/ueditor/jsp/upload/image/"); //System.out.println(arFiles); /*//只遍历指定目录下的文件名 String[] names = f.getFileNameList("test1"); for(String name : names) { System.out.println(new String(name.getBytes("iso-8859-1"), "GB2312")); } //下载 boolean b = f.get("/test1/测试2.txt", "d:/text.txt"); System.out.println(b); //删除 String ftpDirAndFileName = "test1/测试.txt"; boolean be = f.deleteFile(new String(ftpDirAndFileName.getBytes(), "iso-8859-1")); System.out.println(be); //删除目录 boolean delf = f.deleteDirectory("test1"); System.out.println(delf);*/ f.close(); } } catch (Exception e) { e.printStackTrace(); } } public String getServer() { return server; } public void setServer(String server) { this.server = server; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } /** * * <p class="detail"> * 功能:重新命名文件 * </p> * @author wangsheng * @date 2014年9月25日 * @return */ private String getFileNameNew(){ SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS"); return fmt.format(new Date()); } private String getFileFolder(){ SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); return fmt.format(new Date()); } public String getPhotoAllowSuffix() { return photoAllowSuffix; } public void setPhotoAllowSuffix(String photoAllowSuffix) { this.photoAllowSuffix = photoAllowSuffix; } }
上传代码
/** * 公共上传图片 * * @param file * @return */ @ResponseBody @RequestMapping("/uploadPicture") public String uploadPicture(@RequestParam("file") MultipartFile file, @RequestParam("destDir") String destDir) { String fileName = ""; try { switch (destDir) { case Constant.SCHBUILD: fileName = new FtpUtils(ftpModel).uploadsPhoto(file, Constant.SCHBUILD); break; default: break; } } catch (Exception ex) { logger.error("uploadPicture -=- {}", ex.toString()); } return fileName; } /** * 上传图片 判断文件类型 * * @param file 文件 * @param destDir 路径名称 * @return */ @ResponseBody @RequestMapping("/uploadPictureReturnModel") public FileModel uploadPictureReturnModel(@RequestParam("file") MultipartFile file, @RequestParam("destDir") String destDir) { FileModel fileModel = new FileModel(); try { switch (destDir) { case Constant.USER: fileModel = new FtpUtils(ftpModel).uploadsPhotoReturnModel(file, Constant.USER); break; default: break; } } catch (Exception ex) { logger.error("uploadPictureReturnModel -=- {}", ex.toString()); } return fileModel; } /** * 上传图片 多文件使用 判断图片类型 * * @param files 文件数组 * @param destDir 路径名称 * @return */ @ResponseBody @RequestMapping("/uploadPicturesReturnModel") public List<FileModel> uploadPicturesReturnModel(@RequestParam("files") MultipartFile[] files, @RequestParam("destDir") String destDir) { List<FileModel> fileModels = new ArrayList<>(); try { switch (destDir) { case Constant.USER: fileModels = new FtpUtils(ftpModel).uploadsPhotoReturnModel(files, Constant.USER); break; default: break; } } catch (Exception ex) { logger.error("uploadPicturesReturnModel -=- {}", ex.toString()); } return fileModels; } /** * 上传文件 不判断文件类型 * * @param file 文件 * @param destDir 路径名称 * @return */ @ResponseBody @RequestMapping("/uploadFileReturnModel") public FileModel uploadFileReturnModel(@RequestParam("file") MultipartFile file, @RequestParam("destDir") String destDir) { FileModel fileModel = new FileModel(); try { switch (destDir) { case Constant.FILEINFO: fileModel = new FtpUtils(ftpModel).uploadsFileReturnModel(file, Constant.FILEINFO); break; default: break; } } catch (Exception ex) { logger.error("uploadFileReturnModel -=- {}", ex.toString()); } return fileModel; } /** * 上传多文件 不判断文件类型 * * @param files 文件数据 * @param destDir 路径名称 * @return */ @ResponseBody @RequestMapping("/uploadFilesReturnModel") public List<FileModel> uploadFilesReturnModel(@RequestParam("files") MultipartFile[] files, @RequestParam("destDir") String destDir) { List<FileModel> fileModels = new ArrayList<>(); try { switch (destDir) { case Constant.FILEINFO: fileModels = new FtpUtils(ftpModel).uploadsFileReturnModel(files, Constant.FILEINFO); break; default: break; } } catch (Exception ex) { logger.error("uploadFilesReturnModel -=- {}", ex.toString()); } return fileModels; } /** * 查看图片 * * @param response * @param path 图片路径 */ @RequestMapping("/showPhoto") public void showPhoto(HttpServletResponse response, String path) { try { if (StringUtils.isNotEmpty(path)) { //Thread.sleep(500); new FtpUtils(ftpModel).showPhoto(response, path); } } catch (Exception ex) { logger.error("showPhoto -=- {}", ex.toString()); } }
/** * UEditor 查看图片使用 * @param response * @param path */ @RequestMapping("/showPhotoUE") public void showPhotoUE(HttpServletResponse response, String path) { try { String newPath = ""; if (path.contains("?") && StringUtils.isNotEmpty(path)){ newPath = path.substring(0,path.lastIndexOf("?")); }else { newPath = path; } if (StringUtils.isNotEmpty(newPath)) { //Thread.sleep(500); new FtpUtils().showPhoto(response, newPath); } } catch (Exception ex) { logger.error("showPhoto -=- {}", ex.toString()); } }
/** * 下载文件 * * @param response * @param filename 文件名称 * @param path 地址 */ @RequestMapping("/download") public void download(HttpServletResponse response, @RequestParam("filename") String filename, @RequestParam("path") String path) { try { if (StringUtils.isNotEmpty(path) && StringUtils.isNotEmpty(filename)) { //Thread.sleep(500); new FtpUtils().downloadFile(response, filename, path); } } catch (Exception ex) { logger.error("download -=- {}", ex.toString()); } } /** * 查询相册 * * @param destDir 路径名称 * @param id model的id * @return */ @ResponseBody @RequestMapping(value = "/showPhotoAlbum", method = RequestMethod.GET) public LayerPhoto showPhotoForId(HttpServletRequest request, @RequestParam("destDir") String destDir, Long id) { LayerPhoto layerPhoto = null; try { switch (destDir) { } } catch (Exception ex) { logger.error("showPhoto -=- {}", ex.toString()); } return layerPhoto; } @ResponseBody @RequestMapping(value = "/getUeditorConfig") public String getUed(HttpServletRequest request,HttpServletResponse response) { String json=""; try { //String rootPath=request.getServletContext().getRealPath("/"); String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath(); //System.out.println(request.getParameter("action")); json = new ActionEnter( request, rootPath+"static\\content\\plugins\\ueditor\\" ).exec();; logger.info(json); } catch (Exception ex) { logger.error("showPhoto -=- {}", ex.toString()); } return json; }
public class FileModel { private String name;//名字 private String path;//地址 private long size;//大小 private String contentType;//获取文件MIME类型 private String suffix;//文件后缀名 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public long getSize() { return size; } public void setSize(long size) { this.size = size; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public FileModel() { } public FileModel(String name, String path, long size, String contentType, String suffix) { this.name = name; this.path = path; this.size = size; this.contentType = contentType; this.suffix = suffix; } @Override public String toString() { return "FileModel{" + "name='" + name + '\'' + ", path='" + path + '\'' + ", size=" + size + ", contentType='" + contentType + '\'' + ", suffix='" + suffix + '\'' + '}'; } }
layer图片查看
$.get('${ctx}/showPhotoAlbum?destDir=hidden&id=' + value, function (json) { layer.photos({ photos: json }); });