Java project: Design and implementation of online Heihei network disk system (java+Springboot+ssm+mysql+maven)

Source code acquisition: Download from “Resources” on the blog homepage!

1. Brief description of the project

Function: User’s email registration, verification code verification and user login. There is no need to register an account, and you can also upload temporary files that meet the conditions, but they are only valid for 4 hours. File management, upload, download, rename, delete, view statistical data, classification management, etc. Folder management, creation, deletion, renaming. File sharing supports sharing through Lianbokou QR code, etc.

2. Project operation

Environment configuration: Jdk1.8 + Tomcat8.5 + mysql + Eclispe (IntelliJ IDEA, Eclispe, MyEclispe, Sts are all supported)

Project technology: JSP + Springboot + SpringMVC + MyBatis + ThymeLeaf + FTP + JavaScript + JQuery + Ajax + maven, etc.

Administrator controller:

/**
 * @ClassName: AdminController
 * @Description: Administrator controller
 **/
@Controller
public class AdminController extends BaseController {
    private Logger logger = LogUtils.getInstance(AdminController.class);
    
    /**
     * @Description Go to user management page
     * @Author xw
     * @Date 15:11 2020/3/10
     * @Param [map]
     * @return java.lang.String
     **/
    @GetMapping("/manages-users")
    public String manageUsers(Map<String,Object> map,Integer cur){
        if (loginUser.getRole() == 1){
            //for no access rights
            logger.error("Current logged in user:"+loginUser.getUserName()+"No administrator rights!");
            return "redirect:/error401Page";
        }
        //Get all users
        Integer usersCount = userService.getUsersCount();
        //Get the number of pages currently queried, if it is empty, the default is 0
        cur = (cur == null || cur<0)?0:cur;
        //Get statistics
        FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId());
        //Page to get 20 user information
        Page<Object> page = PageHelper.startPage(cur, 20);
        List<UserToShow> users = userService.getUsers();
        map.put("statistics", statistics);
        map.put("users", users);
        map.put("page", page);
        map.put("usersCount", usersCount);
        logger.info("Contents of user management domain:"+map);
        return "admin/manage-users";
    }

    /**
     * @Description Modify user permissions and maximum capacity
     * @Author xw
     * @Date 18:20 2020/3/10
     * @Param [uId, pre, size]
     * @return java.lang.String
     **/
    @GetMapping("/updateStoreInfo")
    @ResponseBody
    public String updateStoreInfo(Integer uId,Integer pre,Integer size){
        Integer integer = fileStoreService.updatePermission(uId, pre, size*1024);
        if (integer == 1) {
            //Update successful, return 200 status code
            logger.info("Modify user"+userService.queryById(uId).getUserName()+": permissions and warehouse size successfully!");
            return "200";
        }else {
            //Update failed, returning 500 status code
            logger.error("Modify user"+userService.queryById(uId).getUserName()+": Failed to modify permissions and warehouse size!");
            return "500";
        }
    }

    /**
     * @Description delete user
     * @Author xw
     * @Date 18:44 2020/3/10
     * @Param [uId, cur]
     * @return java.lang.String
     **/
    @GetMapping("/deleteUser")
    public String deleteUser(Integer uId,Integer cur){
        cur = (cur == null || cur < 0)?1:cur;
        User user = userService.queryById(uId);
        FileStore fileStore = fileStoreService.getFileStoreByUserId(uId);
        List<FileFolder> folders = fileFolderService.getRootFoldersByFileStoreId(fileStore.getFileStoreId());
        //Iteratively delete folders
        for (FileFolder f:folders) {
            deleteFolderF(f);
        }
        List<MyFile> files = myFileService.getRootFilesByFileStoreId(fileStore.getFileStoreId());
        //Delete all files in the root directory of the user's warehouse
        for (MyFile f:files) {
            String remotePath = f.getMyFilePath();
            String fileName = f.getMyFileName()+f.getPostfix();
            //Delete files from FTP file server
            boolean b = FtpUtil.deleteFile("/"+remotePath, fileName);
            if (b){
                //Delete successfully, return space
                fileStoreService.subSize(f.getFileStoreId(),Integer.valueOf(f.getSize()));
                //Delete the data corresponding to the file table
                myFileService.deleteByFileId(f.getMyFileId());
            }
            logger.info("File deleted successfully!"+f);
        }
        if (FtpUtil.deleteFolder("/" + uId)){
            logger.info("Cleared the user's files on FTP successfully");
        }else {
            logger.error("Failed to clear the user's files on FTP");
        }
        userService.deleteById(uId);
        fileStoreService.deleteById(fileStore.getFileStoreId());
        return "redirect:/manages-users?cur="+cur;
    }

    /**
     * @Description Iteratively delete all files and subfolders in the folder
     * @Author xw
     * @Date 9:17 2020/2/29
     * @Param [folder]
     * @return void
     **/
    public void deleteFolderF(FileFolder folder){
        //Get all subfolders under the current folder
        List<FileFolder> folders = fileFolderService.getFileFolderByParentFolderId(folder.getFileFolderId());
        //Delete all files in the current folder
        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());
    }
}

Login to the controller:

/**
* @Description Login controller
* @return
**/
@Controller
public class LoginController extends BaseController {
private Logger logger = LogUtils.getInstance(LoginController.class);
/**
* @Description Login-free user entrance, used for local development and testing. For online operation, please delete this method for security reasons
* @Author xw
* @Date 15:17 2020/2/26
* @Param []
* @return java.lang.String
**/
@GetMapping("/admin")
public String adminLogin(){
User user = userService.getUserByOpenId("123456");
logger.info("Login successfully using login-free method!"+user);
session.setAttribute("loginUser", user);
return "redirect:/index";
}
/**
* For the registration process, verification work such as username, password, email, etc. is completed by the front end
*
* @param map is used to store prompt information
* @author GGBOY
* @date 2020/1/28
*/
@PostMapping("/register")
public String register(User user, String code, Map<String, Object> map) {
String uCode = (String) session.getAttribute(user.getEmail() + "_code");
if (!code.equals(uCode)) {
map.put("errorMsg", "Verification code error");
return "index";
}
//Remove spaces from username
user.setUserName(user.getUserName().trim());
user.setImagePath("https://p.qpic.cn/qqconnect/0/app_101851241_1582451550/100?max-age=2592000&t=0");
user.setRegisterTime(new Date());
user.setRole(1);
if (userService.insert(user)) {
FileStore store = FileStore.builder().userId(user.getUserId()).currentSize(0).build();
fileStoreService.addFileStore(store);
user.setFileStoreId(store.getFileStoreId());
userService.update(user);
logger.info("Registered user successfully! Current registered user" + user);
logger.info("Registration of warehouse successfully! Currently registered warehouse" + store);
} else {
map.put("errorMsg", "An error occurred on the server and registration failed");
return "index";
}
session.removeAttribute(user.getEmail() + "_code");
session.setAttribute("loginUser", user);
return "redirect:/index";
}
/**
* User login
* @param map stores prompt information
* @return java.lang.String
* @author Moti
* @date 2020/1/28
*/
@PostMapping("/login")
public String login(User user, Map<String, Object> map) {
User userByEmail = userService.getUserByEmail(user.getEmail());
if (userByEmail != null && userByEmail.getPassword().equals(user.getPassword())) {
session.setAttribute("loginUser", userByEmail);
logger.info("Login successful!"+userByEmail);
return "redirect:/index";
}else{
User user1 = userService.getUserByEmail(user.getEmail());
String errorMsg = user1 == null ? "This email address has not been registered yet" : "Wrong password";
logger.info("Login failed! Please confirm whether your email and password are correct!");
//Login failed, return failure information to front-end rendering
map.put("errorMsg", errorMsg);
return "index";
}
}
/**
* @return void
* @Description Send a verification code to the registered email address and verify whether the email address has been used
* @Author xw
* @Date 19:32 2020/1/29
* @Param [userName, email, password]
**/
@ResponseBody
@RequestMapping("/sendCode")
public String sendCode(String userName, String email, String password) {
User userByEmail = userService.getUserByEmail(email);
if (userByEmail != null) {
logger.error("Failed to send verification code! Email has been registered!");
return "exitEmail";
}
logger.info("Start sending mail.../n" + "The obtained mail sending object is:" + mailSender);
mailUtils = new MailUtils(mailSender);
String code = "123456";
session.setAttribute(email + "_code", code);
return "success";
}
/**
* @Description Request QQ login
* @Author xw
* @Date 18:27 2020/2/25
* @Param []
* @return void
**/
@GetMapping("/loginByQQ")
public void login() {
response.setContentType("text/html;charset=utf-8");
try {
response.sendRedirect(new Oauth().getAuthorizeURL(request));
logger.info("Request QQ login, start jumping...");
} catch (QQConnectException | IOException e) {
e.printStackTrace();
}
}
/**
* @Description QQ login callback address
* @Author xw
* @Date 18:27 2020/2/25
* @Param []
* @return java.lang.String
**/
@GetMapping("/connection")
public String connection() {
try {
AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
String accessToken = null, openID = null;
long tokenExpireIn = 0L;
if ("".equals(accessTokenObj.getAccessToken())) {
logger.error("Login failed: no response parameters were obtained");
return "accessTokenObj=>" + accessTokenObj + "; accessToken" + accessTokenObj.getAccessToken();
} else {
accessToken = accessTokenObj.getAccessToken();
tokenExpireIn = accessTokenObj.getExpireIn();
logger.error("accessToken" + accessToken);
request.getSession().setAttribute("demo_access_token", accessToken);
request.getSession().setAttribute("demo_token_expirein", String.valueOf(tokenExpireIn));
//Use the obtained accessToken to obtain the currently used openid -------- start
OpenID openIDObj = new OpenID(accessToken);
openID = openIDObj.getUserOpenID();
UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
if (userInfoBean.getRet() == 0) {
logger.info("User's OPEN_ID: " + openID);
logger.info("User's Nickname: " + removeNonBmpUnicode(userInfoBean.getNickname()));
logger.info("User's avatar URI: " + userInfoBean.getAvatar().getAvatarURL100());
//Set user information
User user = userService.getUserByOpenId(openID);
if (user == null){
user = User.builder()
.openId(openID).userName(removeNonBmpUnicode(userInfoBean.getNickname()))
.imagePath(userInfoBean.getAvatar().getAvatarURL100()).
registerTime(new Date()).build();
if (userService.insert(user)){
logger.info("Registered user successfully! Current registered user" + user);
FileStore store = FileStore.builder().userId(user.getUserId()).build();
if (fileStoreService.addFileStore(store) == 1){
user.setFileStoreId(store.getFileStoreId());
userService.update(user);
logger.info("Registration of warehouse successfully! Currently registered warehouse" + store);
}
} else {
logger.error("Failed to register user!");
}
}else {
user.setUserName(removeNonBmpUnicode(userInfoBean.getNickname()));
user.setImagePath(userInfoBean.getAvatar().getAvatarURL100());
userService.update(user);
}
logger.info("QQ user login successfully!"+user);
session.setAttribute("loginUser", user);
return "redirect:/index";
} else {
logger.error("Sorry, we could not obtain your information correctly. The reason is: " + userInfoBean.getMsg());
}
}
} catch (QQConnectException e) {
} finally {
logger.error("Login successful!");
}
return "Login failed! Please check the log information...";
}
/**
* @Description Process the special emoticons in the QQ screen name
* @Author xw
* @Date 18:26 2020/2/25
* @Param [str]
* @return java.lang.String returns the processed network name
**/
public String removeNonBmpUnicode(String str) {
if (str == null) {
return null;
}
str = str.replaceAll("[^\\u0000-\\uFFFF]", "");
if ("".equals(str)) {
str = "($ _ $)";
}
return str;
}
/**
* @Description Log out and clear the session
* @Author xw
* @Date 18:26 2020/2/25
* @Param []
* @return java.lang.String
**/
@GetMapping("/logout")
public String logout() {
logger.info("User logs out!");
session.invalidate();
return "redirect:/";
}
}

File warehouse controller:

/**
* @ClassName: FileStoreController
* @Description: File warehouse controller
**/
@Controller
public class FileStoreController extends BaseController {
private Logger logger = LogUtils.getInstance(FileStoreController.class);
/**
* @Description Upload temporary files
* @Author xw
* @Date 23:14 2020/3/9
* @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("Temporary file upload failed! The file name does not meet the specifications...");
session.setAttribute("msg", "Upload failed! The file name does not meet the specification");
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())){
//Upload successful
logger.info("Temporary file uploaded successfully!"+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()){
//The file does not exist, start generating the QR code and save the file
OutputStream os = new FileOutputStream(f);
QRCodeUtil.encode(url, "/static/img/logo.png", os, true);
os.close();
}
//Delete temporary files asynchronously
tempFileService.deleteById(tempFile.getFileId());
session.setAttribute("imgPath","user_img/"+id+".jpg");
session.setAttribute("url",url);
session.setAttribute("msg","Upload successful, scan the code/visit the link to download!");
return "redirect:/temp-file";
} catch (Exception e) {
e.printStackTrace();
}
}else {
logger.info("Temporary file database writing failed!"+name);
session.setAttribute("url","error");
session.setAttribute("msg", "The server has an error and the temporary file upload failed!");
}
}else{
//upload failed
logger.info("Temporary file upload failed!"+name);
session.setAttribute("url","error");
session.setAttribute("msg", "The server has an error and the upload failed!");
}
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/temp-file";
}
/**
* @Description File upload to network disk
* @Author xw
* @Date 23:10 2020/2/10
* @Param [files]
* @return java.util.Map<java.lang.String,java.lang.Object>
**/
@PostMapping("/uploadFile")
@ResponseBody
public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile files) {
Map<String, Object> map = new HashMap<>();
if (fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission() != 0){
logger.error("The user does not have the permission to upload files! The upload failed...");
map.put("code", 499);
return map;
}
FileStore store = fileStoreService.getFileStoreByUserId(loginUser.getUserId());
Integer folderId = Integer.valueOf(request.getHeader("id"));
String name = files.getOriginalFilename().replaceAll(" ","");
//Get all files in the current directory to determine whether they already exist
List<MyFile> myFiles = null;
if (folderId == 0){
//The current directory is the root directory
myFiles = myFileService.getRootFilesByFileStoreId(loginUser.getFileStoreId());
}else {
//The current directory is another directory
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("The current file already exists! Upload failed...");
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("Upload failed! The file name does not meet the specification...");
map.put("code", 502);
return map;
}
Integer sizeInt = Math.toIntExact(files.getSize() / 1024);
//Whether the warehouse cannot hold the file
if(store.getCurrentSize()+sizeInt > store.getMaxSize()){
logger.error("Upload failed! The warehouse is full.");
map.put("code", 503);
return map;
}
//Handle file size
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);
//Get the file type
type = getType(tempName.toLowerCase());
postfix = tempName.toLowerCase();
}
try {
//Submit to FTP server
boolean b = FtpUtil.uploadFile("/"+path, name + postfix, files.getInputStream());
if (b){
//Upload successful
logger.info("File uploaded successfully!"+files.getOriginalFilename());
//Write data to database file table
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());
//Update the current size of the warehouse table
fileStoreService.addSize(store.getFileStoreId(),Integer.valueOf(size));
try {
Thread.sleep(5000);
map.put("code", 200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
logger.error("File upload failed!"+files.getOriginalFilename());
map.put("code", 504);
}
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
/**
* @Description File download from network disk 
* @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("The user does not have permission to download the file! The download failed...");
return "redirect:/error401Page";
}
//Get file information
MyFile myFile = myFileService.getFileByFileId(fId);
String remotePath = myFile.getMyFilePath();
String fileName = myFile.getMyFileName()+myFile.getPostfix();
try {
//Go to FTP to pull
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setCharacterEncoding("utf-8");
//Set return type
response.setContentType("multipart/form-data");
// Convert the file name, otherwise Chinese garbled characters will appear.
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("File downloaded successfully!" + myFile);
}
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
/**
* @Description delete file
* @Author xw
* @Date 23:14 2020/2/10
* @Param [fId, folder]
* @return java.lang.String
**/
@GetMapping("/deleteFile")
public String deleteFile(@RequestParam Integer fId,Integer folder){
//Get file information
MyFile myFile = myFileService.getFileByFileId(fId);
String remotePath = myFile.getMyFilePath();
String fileName = myFile.getMyFileName()+myFile.getPostfix();
//Delete files from FTP file server
boolean b = FtpUtil.deleteFile("/"+remotePath, fileName);
if (b){
//Delete successfully, return space
fileStoreService.subSize(myFile.getFileStoreId(),Integer.valueOf(myFile.getSize()));
//Delete the data corresponding to the file table
myFileService.deleteByFileId(fId);
}
logger.info("File deleted successfully!"+myFile);
return "redirect:/files?fId="+folder;
}
/**
* @Description delete file夹并清空文件
* @Author xw
* @Date 15:22 2020/2/12
* @Param [fId]
* @return java.lang.String
**/
@GetMapping("/deleteFolder")
public String deleteFolder(@RequestParam Integer fId){
FileFolder folder = fileFolderService.getFileFolderByFileFolderId(fId);
//forced deletion
deleteFolderF(folder);
return folder.getParentFolderId() == 0?"redirect:/files":"redirect:/files?fId="+folder.getParentFolderId();
} 
/**
* @Description Iteratively delete all files and subfolders in the folder
* @Author xw
* @Date 9:17 2020/2/29
* @Param [folder]
* @return void
**/
public void deleteFolderF(FileFolder folder){
//Get all subfolders under the current folder
List<FileFolder> folders = fileFolderService.getFileFolderByParentFolderId(folder.getFileFolderId());
//Delete all files in the current folder
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 add folder
* @Author xw
* @Date 23:16 2020/2/10
* @Param [folder, map]
* @return java.lang.String
**/
@PostMapping("/addFolder")
public String addFolder(FileFolder folder,Map<String, Object> map) {
//Set folder information
folder.setFileStoreId(loginUser.getFileStoreId());
folder.setTime(new Date());
//Get all folders in the current directory and check whether the current folder already exists
List<FileFolder> fileFolders = null;
if (folder.getParentFolderId() == 0){
//Add a folder to the user root directory
fileFolders = fileFolderService.getRootFoldersByFileStoreId(loginUser.getFileStoreId());
}else{
//Add folders to the user's other directories
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("Failed to add folder! Folder already exists...");
return "redirect:/files?error=1&fId="+folder.getParentFolderId();
}
}
//Write data to the database
Integer integer = fileFolderService.addFileFolder(folder);
logger.info("Add folder successfully!"+folder);
return "redirect:/files?fId="+folder.getParentFolderId();
}
/**
* @Description Rename folder
* @Author xw
* @Date 23:18 2020/2/10
* @Param [folder, map]
* @return java.lang.String
**/
@PostMapping("/updateFolder")
public String updateFolder(FileFolder folder,Map<String, Object> map) {
//Get the database information of the folder
FileFolder fileFolder = fileFolderService.getFileFolderByFileFolderId(folder.getFileFolderId());
fileFolder.setFileFolderName(folder.getFileFolderName());
//Get all folders in the current directory to check whether the folder already exists
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("Failed to rename folder! Folder already exists...");
return "redirect:/files?error=2&fId="+fileFolder.getParentFolderId();
}
}
//Write data to the database
Integer integer = fileFolderService.updateFileFolderById(fileFolder);
logger.info("Renamed folder successfully!"+folder);
return "redirect:/files?fId="+fileFolder.getParentFolderId();
}
/**
* @Description Rename file
* @Author xw
* @Date 12:47 2020/2/12
* @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("The file name was modified successfully! Original file name: "+oldName+" New file name: "+newName);
}else{
logger.error("Failed to modify file name! Original file name: "+oldName+" New file name: "+newName);
}
}
}
}
return "redirect:/files?fId="+myFile.getParentFolderId();
}
/**
* @Description Get the QR code 
* @Author xw
* @Date 15:20 2020/2/12
* @Param [id, url]
* @return java.util.Map<java.lang.String,java.lang.Object>
**/
@GetMapping("getQrCode")
@ResponseBody
public 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()){
//The file does not exist, start generating the QR code and save the file
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 Share files
* @Author xw
* @Date 14:23 2020/2/12
* @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("Failed to download shared file, parameter error");
return "redirect:/error400Page";
}
if(flag == 1){
//Get file information
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 {
//Solve the problem of garbled Chinese file names when downloading files
boolean isMSIE = isMSBrowser(request);
if (isMSIE) {
//Solution to the garbled code problem of IE browser
fileNameTemp = URLEncoder.encode(fileNameTemp, "UTF-8");
} else {
//Universal garbled code problem solution
fileNameTemp = new String(fileNameTemp.getBytes("UTF-8"), "ISO-8859-1");
}
//Go to FTP to pull
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setCharacterEncoding("utf-8");
//Set return type
response.setContentType("multipart/form-data");
// Convert the file name, otherwise Chinese garbled characters will appear.
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("File downloaded successfully!");
}
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
/**
* @Description Get the corresponding type based on the file suffix name
* @Author xw
* @Date 23:20 2020/2/10
* @Param [type]
* @return int 1: Text type 2: Image type 3: Video type 4: Music type 5: Other types
**/
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 Regularly verifies whether the file name is legal [Chinese characters, characters, numbers, underlines, English periods, horizontal lines]
* @Author xw
* @Date 23:22 2020/2/10
* @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 Determine whether the current browser is ie
* @Author xw
* @Date 22:39 2020/3/5
* @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;
}
}

Source code acquisition: Download from “Resources” on the blog homepage!

Related Posts

[Exception]The field file exceeds its maximum permitted size of 1,048,576 bytes.

Android studio button click page jump

Junit unit testing

From shallow to deep, I will take you through the three ways to implement array expansion in Java [recommended collection]

Java connects to the database to implement basic additions, deletions, modifications and queries

[JavaSE] Multi-threading (3) User threads, daemon threads and seven major states of threads

When adding dependencies to pom files, an unknown problem occurs [maven]. A complete solution to dependency error reporting in maven projects.

A simple tutorial on how to use the MybatisX plug-in in SpringBoot (super detailed!!)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*