Java操作FTP服务器(下)

devtools/2024/12/26 20:32:26/

        Windwos中搭建FPT可以查看我的一篇文章《windows搭建ftp服务器(上)》        

        Java 操作 FTP 服务器通常使用 Apache Commons Net 库,这是一个功能强大的网络库,支持多种协议,包括 FTP。

       一、我们需要在pom.xml中引入相应依赖:

<!--引入FTP 依赖-->
<dependency><groupId>commons-net</groupId><artifactId>commons-net</artifactId><version>3.6</version>
</dependency>

        二、FTP操作工具类,包括基本的文件上传、下载、删除

java">package com.xxl.utils;import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;import java.io.*;
import java.util.ArrayList;
import java.util.List;/*** @ClassName: FtpUtil* @Description: FTP工具类* @Version: 1.0**/
public class FtpUtil {/*** FTP服务器hostname*/private static String HOST = "192.168.1.109";/*** FTP服务器端口*/private static int PORT = 21;/*** FTP登录账号*/private static String USERNAME = "ftptest";/*** FTP登录密码*/private static String PASSWORD = "qwer1234";/*** FTP服务器基础目录*/private static String BASEPATH = "";/*** FTP客户端*/private static FTPClient ftp;/*** @Description 初始化FTP客户端* @Param []* @return boolean**/public static boolean initFtpClient(){ftp = new FTPClient();int reply;try {// 连接FTP服务器ftp.connect(HOST, PORT);//登录, 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器ftp.login(USERNAME, PASSWORD);ftp.setBufferSize(10240);//设置传输超时时间为60秒ftp.setDataTimeout(600000);//连接超时为60秒ftp.setConnectTimeout(600000);//FTP以二进制形式传输ftp.setFileType(FTP.BINARY_FILE_TYPE);reply = ftp.getReplyCode();if (!FTPReply.isPositiveCompletion(reply)) {ftp.disconnect();return false;}} catch (IOException e) {e.printStackTrace();}return true;}/*** Description: 向FTP服务器上传文件* @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath* @param filename 上传到FTP服务器上的文件名* @param input 本地要上传的文件的 输入流* @return 成功返回true,否则返回false*/public static boolean uploadFile(String filePath, String filename, InputStream input) {boolean result = false;try {filePath = new String(filePath.getBytes("GBK"),"iso-8859-1");filename = new String(filename.getBytes("GBK"),"iso-8859-1");if (!initFtpClient()){return result;};//切换到上传目录ftp.enterLocalPassiveMode();if (!ftp.changeWorkingDirectory(BASEPATH+filePath)) {//如果目录不存在创建目录String[] dirs = filePath.split("/");String tempPath = BASEPATH;for (String dir : dirs) {if (null == dir || "".equals(dir)){continue;}tempPath += "/" + dir;if (!ftp.changeWorkingDirectory(tempPath)) {if (!ftp.makeDirectory(tempPath)) {return result;} else {ftp.changeWorkingDirectory(tempPath);}}}}//设置上传文件的类型为二进制类型ftp.setFileType(FTP.BINARY_FILE_TYPE);//上传文件ftp.enterLocalPassiveMode();if (!ftp.storeFile(filename, input)) {return result;}input.close();ftp.logout();result = true;}catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return result;}/*** Description: 从FTP服务器下载文件* @param remotePath FTP服务器上的相对路径* @param fileName 要下载的文件名* @return*/public static boolean downloadFile( String remotePath,String fileName,String localPath) {boolean result = false;try {remotePath = new String(remotePath.getBytes("GBK"),"iso-8859-1");fileName = new String(fileName.getBytes("GBK"),"iso-8859-1");if (!initFtpClient()){return result;};// 转移到FTP服务器目录ftp.changeWorkingDirectory(remotePath);ftp.enterLocalPassiveMode();FTPFile[] fs = ftp.listFiles();for (FTPFile ff : fs) {if (ff.getName().equals(fileName)) {ftp.enterLocalPassiveMode();FileOutputStream outputStream = new FileOutputStream(new File(localPath));ftp.retrieveFile(remotePath+"/"+fileName,outputStream);result = true;outputStream.close();}}ftp.logout();} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return result;}/*** @Description 从ftp服务器下载文件到指定输出流* @Param [remotePath, fileName, outputStream]* @return boolean**/public static boolean downloadFile(String remotePath, String fileName, OutputStream outputStream) {boolean result = false;try {remotePath = new String(remotePath.getBytes("GBK"),"iso-8859-1");fileName = new String(fileName.getBytes("GBK"),"iso-8859-1");if (!initFtpClient()){return result;};// 转移到FTP服务器目录ftp.changeWorkingDirectory(remotePath);ftp.enterLocalPassiveMode();FTPFile[] fs = ftp.listFiles();for (FTPFile ff : fs) {if (ff.getName().equals(fileName)) {ftp.enterLocalPassiveMode();ftp.retrieveFile(remotePath+"/"+fileName,outputStream);result = true;}}ftp.logout();} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return result;}/*** @Description 删除文件* @Param [remotePath, fileName]* @return void**/public static boolean deleteFile( String remotePath,String fileName){boolean flag = false;try {remotePath = new String(remotePath.getBytes("GBK"),"iso-8859-1");fileName = new String(fileName.getBytes("GBK"),"iso-8859-1");if (!initFtpClient()){return flag;};// 转移到FTP服务器目录ftp.changeWorkingDirectory(remotePath);ftp.enterLocalPassiveMode();FTPFile[] fs = ftp.listFiles();for (FTPFile ff : fs) {if ("".equals(fileName)){return flag;}if (ff.getName().equals(fileName)){String filePath = remotePath + "/" +fileName;ftp.deleteFile(filePath);flag = true;}}ftp.logout();} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return flag;}/*** @Description 删除文件夹* @Param [remotePath, fileName]* @return void**/public static boolean deleteFolder( String remotePath){boolean flag = false;try {remotePath = new String(remotePath.getBytes("GBK"),"iso-8859-1");if (!initFtpClient()){return flag;};// 转移到FTP服务器目录ftp.changeWorkingDirectory(remotePath);ftp.enterLocalPassiveMode();FTPFile[] fs = ftp.listFiles();if (fs.length==0){ftp.removeDirectory(remotePath);flag = true;}ftp.logout();} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return flag;}/*** @Description 修改文件名称或者文件夹名* @Param [oldAllName, newAllName]* @return boolean**/public static boolean reNameFile( String oldAllName,String newAllName){boolean flag = false;try {oldAllName = new String(oldAllName.getBytes("GBK"),"iso-8859-1");newAllName = new String(newAllName.getBytes("GBK"),"iso-8859-1");if (!initFtpClient()){return flag;};ftp.enterLocalPassiveMode();ftp.rename(oldAllName,newAllName);flag = true;ftp.logout();} catch (IOException e) {e.printStackTrace();} finally {if (ftp.isConnected()) {try {ftp.disconnect();} catch (IOException ioe) {}}}return flag;}
}

        三、控制器编写

java">package com.moti.controller;import com.moti.entity.FileFolder;
import com.moti.entity.FileStore;
import com.moti.entity.MyFile;
import com.moti.entity.TempFile;
import com.moti.utils.FtpUtil;
import com.moti.utils.LogUtils;
import com.moti.utils.QRCodeUtil;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;/*** @ClassName: FileStoreController* @Description: 文件仓库控制器* @Version: 1.0**/
@Controller
public class FileStoreController extends BaseController {private Logger logger = LogUtils.getInstance(FileStoreController.class);/*** @Description 上传临时文件* @Param [files]* @return void**/@PostMapping("/uploadTempFile")public String uploadTempFile(@RequestParam("file") MultipartFile file,String url) {session.setAttribute("imgPath","https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2654852821,3851565636&fm=26&gp=0.jpg");String name = file.getOriginalFilename().replaceAll(" ","");if (!checkTarget(name)){logger.error("临时文件上传失败!文件名不符合规范...");session.setAttribute("msg", "上传失败!文件名不符合规范");return "redirect:/temp-file";}SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");String dateStr = format.format(new Date());String path = "temp/"+dateStr +"/"+UUID.randomUUID();try {if (FtpUtil.uploadFile("/"+path, name, file.getInputStream())){//上传成功logger.info("临时文件上传成功!"+name);String size = String.valueOf(file.getSize());TempFile tempFile = TempFile.builder().fileName(name).filePath(path).size(size).uploadTime(new Date()).build();if (tempFileService.insert(tempFile)) {try {String id = UUID.randomUUID().toString();String p = request.getSession().getServletContext().getRealPath("/user_img/");Long t = tempFile.getUploadTime().getTime();url = url+"/file/share?t="+ UUID.randomUUID().toString().substring(0,10) +"&f="+tempFile.getFileId()+"&p="+size+"&flag=2";File targetFile = new File(p, "");if (!targetFile.exists()) {targetFile.mkdirs();}File f = new File(p, id + ".jpg");if (!f.exists()){//文件不存在,开始生成二维码并保存文件OutputStream os = new FileOutputStream(f);QRCodeUtil.encode(url, "/static/img/logo.png", os, true);os.close();}//异步删除临时文件tempFileService.deleteById(tempFile.getFileId());session.setAttribute("imgPath","user_img/"+id+".jpg");session.setAttribute("url",url);session.setAttribute("msg","上传成功,扫码/访问链接 即可下载!");return "redirect:/temp-file";} catch (Exception e) {e.printStackTrace();}}else {logger.info("临时文件数据库写入失败!"+name);session.setAttribute("url","error");session.setAttribute("msg", "服务器出错了,临时文件上传失败!");}}else{//上传失败logger.info("临时文件上传失败!"+name);session.setAttribute("url","error");session.setAttribute("msg", "服务器出错了,上传失败!");}} catch (IOException e) {e.printStackTrace();}return "redirect:/temp-file";}/*** @Description 网盘的文件上传* @Param [files]* @return java.util.Map<java.lang.String,java.lang.Object>**/@PostMapping("/uploadFile")@ResponseBodypublic Map<String, Object> uploadFile(@RequestParam("file") MultipartFile files) {Map<String, Object> map = new HashMap<>();if (fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission() != 0){logger.error("用户没有上传文件的权限!上传失败...");map.put("code", 499);return map;}FileStore store = fileStoreService.getFileStoreByUserId(loginUser.getUserId());Integer folderId = Integer.valueOf(request.getHeader("id"));String name = files.getOriginalFilename().replaceAll(" ","");//获取当前目录下的所有文件,用来判断是否已经存在List<MyFile> myFiles = null;if (folderId == 0){//当前目录为根目录myFiles = myFileService.getRootFilesByFileStoreId(loginUser.getFileStoreId());}else {//当前目录为其他目录myFiles = myFileService.getFilesByParentFolderId(folderId);}for (int i = 0; i < myFiles.size(); i++) {if ((myFiles.get(i).getMyFileName()+myFiles.get(i).getPostfix()).equals(name)){logger.error("当前文件已存在!上传失败...");map.put("code", 501);return map;}}SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");String dateStr = format.format(new Date());String path = loginUser.getUserId()+"/"+dateStr +"/"+folderId;if (!checkTarget(name)){logger.error("上传失败!文件名不符合规范...");map.put("code", 502);return map;}Integer sizeInt = Math.toIntExact(files.getSize() / 1024);//是否仓库放不下该文件if(store.getCurrentSize()+sizeInt > store.getMaxSize()){logger.error("上传失败!仓库已满。");map.put("code", 503);return map;}//处理文件大小String size = String.valueOf(files.getSize()/1024.0);int indexDot = size.lastIndexOf(".");size = size.substring(0,indexDot);int index = name.lastIndexOf(".");String tempName = name;String postfix = "";int type = 4;if (index!=-1){tempName = name.substring(index);name = name.substring(0,index);//获得文件类型type = getType(tempName.toLowerCase());postfix = tempName.toLowerCase();}try {//提交到FTP服务器boolean b = FtpUtil.uploadFile("/"+path, name + postfix, files.getInputStream());if (b){//上传成功logger.info("文件上传成功!"+files.getOriginalFilename());//向数据库文件表写入数据myFileService.addFileByFileStoreId(MyFile.builder().myFileName(name).fileStoreId(loginUser.getFileStoreId()).myFilePath(path).downloadTime(0).uploadTime(new Date()).parentFolderId(folderId).size(Integer.valueOf(size)).type(type).postfix(postfix).build());//更新仓库表的当前大小fileStoreService.addSize(store.getFileStoreId(),Integer.valueOf(size));try {Thread.sleep(5000);map.put("code", 200);} catch (InterruptedException e) {e.printStackTrace();}}else{logger.error("文件上传失败!"+files.getOriginalFilename());map.put("code", 504);}} catch (IOException e) {e.printStackTrace();}return map;}/*** @Description 网盘的文件下载 * @Author xw* @Date 23:13 2020/2/10* @Param [fId]* @return void**/@GetMapping("/downloadFile")public String downloadFile(@RequestParam Integer fId){if (fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission() == 2){logger.error("用户没有下载文件的权限!下载失败...");return "redirect:/error401Page";}//获取文件信息MyFile myFile = myFileService.getFileByFileId(fId);String remotePath = myFile.getMyFilePath();String fileName = myFile.getMyFileName()+myFile.getPostfix();try {//去FTP上拉取OutputStream os = new BufferedOutputStream(response.getOutputStream());response.setCharacterEncoding("utf-8");// 设置返回类型response.setContentType("multipart/form-data");// 文件名转码一下,不然会出现中文乱码response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));boolean flag = FtpUtil.downloadFile("/" + remotePath, fileName, os);if (flag) {myFileService.updateFile(MyFile.builder().myFileId(myFile.getMyFileId()).downloadTime(myFile.getDownloadTime() + 1).build());os.flush();os.close();logger.info("文件下载成功!" + myFile);}} catch (Exception e) {e.printStackTrace();}return "success";}/*** @Description 删除文件* @Param [fId, folder]* @return java.lang.String**/@GetMapping("/deleteFile")public String deleteFile(@RequestParam Integer fId,Integer folder){//获得文件信息MyFile myFile = myFileService.getFileByFileId(fId);String remotePath = myFile.getMyFilePath();String fileName = myFile.getMyFileName()+myFile.getPostfix();//从FTP文件服务器上删除文件boolean b = FtpUtil.deleteFile("/"+remotePath, fileName);if (b){//删除成功,返回空间fileStoreService.subSize(myFile.getFileStoreId(),Integer.valueOf(myFile.getSize()));//删除文件表对应的数据myFileService.deleteByFileId(fId);}logger.info("删除文件成功!"+myFile);return "redirect:/files?fId="+folder;}/*** @Description 删除文件夹并清空文件* @Param [fId]* @return java.lang.String**/@GetMapping("/deleteFolder")public String deleteFolder(@RequestParam Integer fId){FileFolder folder = fileFolderService.getFileFolderByFileFolderId(fId);//强制删除deleteFolderF(folder);return folder.getParentFolderId() == 0?"redirect:/files":"redirect:/files?fId="+folder.getParentFolderId();} /*** @Description 迭代删除文件夹里面的所有文件和子文件夹* @Param [folder]* @return void**/public void deleteFolderF(FileFolder folder){//获得当前文件夹下的所有子文件夹List<FileFolder> folders = fileFolderService.getFileFolderByParentFolderId(folder.getFileFolderId());//删除当前文件夹的所有的文件List<MyFile> files = myFileService.getFilesByParentFolderId(folder.getFileFolderId());if (files.size()!=0){for (int i = 0; i < files.size(); i++) {Integer fileId = files.get(i).getMyFileId();boolean b = FtpUtil.deleteFile("/"+files.get(i).getMyFilePath(), files.get(i).getMyFileName() + files.get(i).getPostfix());if (b){myFileService.deleteByFileId(fileId);fileStoreService.subSize(folder.getFileStoreId(),Integer.valueOf(files.get(i).getSize()));}}}if (folders.size()!=0){for (int i = 0; i < folders.size(); i++) {deleteFolderF(folders.get(i));}}fileFolderService.deleteFileFolderById(folder.getFileFolderId());}/*** @Description 添加文件夹* @Param [folder, map]* @return java.lang.String**/@PostMapping("/addFolder")public String addFolder(FileFolder folder,Map<String, Object> map) {//设置文件夹信息folder.setFileStoreId(loginUser.getFileStoreId());folder.setTime(new Date());//获得当前目录下的所有文件夹,检查当前文件夹是否已经存在List<FileFolder> fileFolders = null;if (folder.getParentFolderId() == 0){//向用户根目录添加文件夹fileFolders = fileFolderService.getRootFoldersByFileStoreId(loginUser.getFileStoreId());}else{//向用户的其他目录添加文件夹fileFolders = fileFolderService.getFileFolderByParentFolderId(folder.getParentFolderId());}for (int i = 0; i < fileFolders.size(); i++) {FileFolder fileFolder = fileFolders.get(i);if (fileFolder.getFileFolderName().equals(folder.getFileFolderName())){logger.info("添加文件夹失败!文件夹已存在...");return "redirect:/files?error=1&fId="+folder.getParentFolderId();}}//向数据库写入数据Integer integer = fileFolderService.addFileFolder(folder);logger.info("添加文件夹成功!"+folder);return "redirect:/files?fId="+folder.getParentFolderId();}/*** @Description 重命名文件夹* @Param [folder, map]* @return java.lang.String**/@PostMapping("/updateFolder")public String updateFolder(FileFolder folder,Map<String, Object> map) {//获得文件夹的数据库信息FileFolder fileFolder = fileFolderService.getFileFolderByFileFolderId(folder.getFileFolderId());fileFolder.setFileFolderName(folder.getFileFolderName());//获得当前目录下的所有文件夹,用于检查文件夹是否已经存在List<FileFolder> fileFolders = fileFolderService.getFileFolderByParentFolderId(fileFolder.getParentFolderId());for (int i = 0; i < fileFolders.size(); i++) {FileFolder folder1 = fileFolders.get(i);if (folder1.getFileFolderName().equals(folder.getFileFolderName()) && folder1.getFileFolderId() != folder.getFileFolderId()){logger.info("重命名文件夹失败!文件夹已存在...");return "redirect:/files?error=2&fId="+fileFolder.getParentFolderId();}}//向数据库写入数据Integer integer = fileFolderService.updateFileFolderById(fileFolder);logger.info("重命名文件夹成功!"+folder);return "redirect:/files?fId="+fileFolder.getParentFolderId();}/*** @Description 重命名文件* @Param [file, map]* @return java.lang.String**/@PostMapping("/updateFileName")public String updateFileName(MyFile file,Map<String, Object> map) {MyFile myFile = myFileService.getFileByFileId(file.getMyFileId());if (myFile != null){String oldName = myFile.getMyFileName();String newName = file.getMyFileName();if (!oldName.equals(newName)){boolean b = FtpUtil.reNameFile(myFile.getMyFilePath() + "/" + oldName+myFile.getPostfix(), myFile.getMyFilePath() + "/" + newName+myFile.getPostfix());if (b){Integer integer = myFileService.updateFile(MyFile.builder().myFileId(myFile.getMyFileId()).myFileName(newName).build());if (integer == 1){logger.info("修改文件名成功!原文件名:"+oldName+"  新文件名:"+newName);}else{logger.error("修改文件名失败!原文件名:"+oldName+"  新文件名:"+newName);}}}}return "redirect:/files?fId="+myFile.getParentFolderId();}/*** @Description 获得二维码 * @Param [id, url]* @return java.util.Map<java.lang.String,java.lang.Object>**/@GetMapping("getQrCode")@ResponseBodypublic Map<String,Object> getQrCode(@RequestParam Integer id,@RequestParam String url){Map<String,Object> map = new HashMap<>();map.put("imgPath","https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2654852821,3851565636&fm=26&gp=0.jpg");if (id != null){MyFile file = myFileService.getFileByFileId(id);if (file != null){try {String path = request.getSession().getServletContext().getRealPath("/user_img/");url = url+"/file/share?t="+ UUID.randomUUID().toString().substring(0,10) +"&f="+file.getMyFileId()+"&p="+file.getUploadTime().getTime()+""+file.getSize()+"&flag=1";File targetFile = new File(path, "");if (!targetFile.exists()) {targetFile.mkdirs();}File f = new File(path, id + ".jpg");if (!f.exists()){//文件不存在,开始生成二维码并保存文件OutputStream os = new FileOutputStream(f);QRCodeUtil.encode(url, "/static/img/logo.png", os, true);os.close();}map.put("imgPath","user_img/"+id+".jpg");map.put("url",url);} catch (Exception e) {e.printStackTrace();}}}return map;}/*** @Description 分享文件* @Param [fId]* @return void**/@GetMapping("/file/share")public String shareFile(Integer f,String p,String t,Integer flag){String fileNameTemp = "";String remotePath = "";String fileName = "";Integer times = 0;if (flag == null || f == null || p == null || t == null){logger.info("下载分享文件失败,参数错误");return "redirect:/error400Page";}if(flag == 1){//获取文件信息MyFile myFile = myFileService.getFileByFileId(f);if (myFile == null){return "redirect:/error404Page";}String pwd = myFile.getUploadTime().getTime()+""+myFile.getSize();if (!pwd.equals(p)){return "redirect:/error400Page";}remotePath = myFile.getMyFilePath();fileName = myFile.getMyFileName()+myFile.getPostfix();}else if(flag == 2){TempFile tempFile = tempFileService.queryById(f);if (tempFile == null){return "redirect:/error404Page";}Long test = tempFile.getUploadTime().getTime();String pwd = tempFile.getSize();if (!pwd.equals(p)){return "redirect:/error400Page";}remotePath = tempFile.getFilePath();fileName = tempFile.getFileName();}else {return "redirect:/error400Page";}fileNameTemp = fileName;try {//解决下载文件时 中文文件名乱码问题boolean isMSIE = isMSBrowser(request);if (isMSIE) {//IE浏览器的乱码问题解决fileNameTemp = URLEncoder.encode(fileNameTemp, "UTF-8");} else {//万能乱码问题解决fileNameTemp = new String(fileNameTemp.getBytes("UTF-8"), "ISO-8859-1");}//去FTP上拉取OutputStream os = new BufferedOutputStream(response.getOutputStream());response.setCharacterEncoding("utf-8");// 设置返回类型response.setContentType("multipart/form-data");// 文件名转码一下,不然会出现中文乱码response.setHeader("Content-Disposition", "attachment;fileName=" + fileNameTemp);if (FtpUtil.downloadFile("/" + remotePath, fileName, os)) {myFileService.updateFile(MyFile.builder().myFileId(f).downloadTime(times + 1).build());os.flush();os.close();logger.info("文件下载成功!");}} catch (Exception e) {e.printStackTrace();}return "success";}/*** @Description 根据文件的后缀名获得对应的类型* @Author xw* @Date 23:20 2020/2/10* @Param [type]* @return int 1:文本类型   2:图像类型  3:视频类型  4:音乐类型  5:其他类型**/public int getType(String type){if (".chm".equals(type)||".txt".equals(type)||".xmind".equals(type)||".xlsx".equals(type)||".md".equals(type)||".doc".equals(type)||".docx".equals(type)||".pptx".equals(type)||".wps".equals(type)||".word".equals(type)||".html".equals(type)||".pdf".equals(type)){return  1;}else if (".bmp".equals(type)||".gif".equals(type)||".jpg".equals(type)||".ico".equals(type)||".vsd".equals(type)||".pic".equals(type)||".png".equals(type)||".jepg".equals(type)||".jpeg".equals(type)||".webp".equals(type)||".svg".equals(type)){return 2;} else if (".avi".equals(type)||".mov".equals(type)||".qt".equals(type)||".asf".equals(type)||".rm".equals(type)||".navi".equals(type)||".wav".equals(type)||".mp4".equals(type)||".mkv".equals(type)||".webm".equals(type)){return 3;} else if (".mp3".equals(type)||".wma".equals(type)){return 4;} else {return 5;}}/*** @Description 正则验证文件名是否合法 [汉字,字符,数字,下划线,英文句号,横线]* @Param [target]* @return boolean**/public boolean checkTarget(String target) {final String format = "[^\\u4E00-\\u9FA5\\uF900-\\uFA2D\\w-_.]";Pattern pattern = Pattern.compile(format);Matcher matcher = pattern.matcher(target);return !matcher.find();}/*** @Description 判断当前浏览器是否为ie* @Param [request]* @return boolean**/public static boolean isMSBrowser(HttpServletRequest request) {String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};String userAgent = request.getHeader("User-Agent");for (String signal : IEBrowserSignals) {if (userAgent.contains(signal)){return true;}}return false;}}


http://www.ppmy.cn/devtools/144044.html

相关文章

mysql的事务控制和数据库的备份和恢复

事务控制语句 行锁和死锁 行锁 两个客户端同时对同一索引行进行操作 客户端1正常运行 客户端2想修改&#xff0c;被锁行 除非将事务提交才能继续运行 死锁 客户端1删除第5行 客户端2设置第1行为排他锁 客户端1删除行1被锁 客户端2更新行5被锁 如何避免死锁 mysql的备份和还…

【自动化部署】Ansible循环

文章目录 Ansible循环1. with_items2. with_list3. with_flattened4. with_together5. with_cartesian 和 with_nested Ansible 配置模板与效率优化一、配置模板1. 准备配置模板文件2. 修改 inventory 主机清单配置文件3. 编写 playbook 二、Ansible 执行效率优化1. 加大 forks…

大恒相机开发(2)—Python软触发调用采集图像

大恒相机开发&#xff08;2&#xff09;—Python软触发调用采集图像 完整代码详细解读和功能说明扩展学习 这段代码是一个Python程序&#xff0c;用于从大恒相机采集图像&#xff0c;通过软件触发来采集图像。 完整代码 咱们直接上python的完整代码&#xff1a; # version:…

linux 服务器安装jdk 1.8

jdk-8u171-linux-x64.tar.gz.temp 通常在下载完成之前都会有一个 .temp 的扩展名。 要安装这个 JDK&#xff0c;您需要执行以下步骤 mv jdk-8u171-linux-x64.tar.gz.temp jdk-8u171-linux-x64.tar.gz tar -zxvf jdk-8u171-linux-x64.tar.gz 创建jdk安装目录 mkdir -p …

wxpyton+wxFormBuilder加法运算示例

wxpythonwxFormBuilder加法运算示例 在wxFormBuilder里设计一个窗体&#xff0c;生成如下代码&#xff1a;calc_From.py 放在lib文件夹下面 import gettext import wx import wx.xrc _ gettext.gettext class MyFrame1(wx.Frame):def __init__(self, parent):wx.Frame.__init…

idea开发工具创建子分支到结束完成流程

以下是基于当前 master 分支进行功能开发、测试、合并到 master 并清除临时分支的完整流程。整个流程将包括命令行操作和使用 IntelliJ IDEA 工具的步骤说明&#xff0c;确保开发过程顺畅且高效。 流程概述 确保 master 分支是最新的创建功能分支在功能分支上进行开发提交并推…

设计模式学习[13]---抽象工厂模式+简单工厂+工厂方法模式回顾

文章目录 前言1.原理阐述1.1 说明11.2 说明2 2.举例 总结 前言 之前写过一些工厂的相关内容&#xff0c;详情见这两篇&#xff1a;简单工厂与工厂方法 这篇博客主要讲抽象工厂模式。 1.原理阐述 1.1 说明1 抽象工厂模式&#xff1a;提供一个创建一系列相关或相互依赖对象的…

MongoDB常见面试题总结(上)

MongoDB 基础 MongoDB 是什么? MongoDB 是一个基于 分布式文件存储 的开源 NoSQL 数据库系统,由 C++ 编写的。MongoDB 提供了 面向文档 的存储方式,操作起来比较简单和容易,支持“无模式”的数据建模,可以存储比较复杂的数据类型,是一款非常流行的 文档类型数据库 。 …