Java畢業設計實戰之在線網盤系統的實現

一、項目簡述

功能:用戶的郵箱註冊、驗證碼驗證以及用戶登錄。 不需要註冊賬號,也可以上傳滿足條件的臨時文件,但是隻4小時內有效。 文件的管理,上傳、下載、重命名、刪除、查看統計數據、分類管理等。 文件夾的管理,創建、刪除、重命名。 文件的分享,支持通過鏈接和二維碼的分享方式等等,以及管理員對用戶的管理等等。

二、項目運行

環境配置:

Jdk1.8 + Tomcat8.5 + mysql + Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)

項目技術:

JSP +Springboot+ SpringMVC + MyBatis + ThymeLeaf + FTP+ JavaScript + JQuery + Ajax + maven等等

文件倉庫控制器:

 /**
 * @ClassName: FileStoreController
 * @Description: 文件倉庫控制器
 **/
@Controller
public class FileStoreController extends BaseController {
    private Logger logger = LogUtils.getInstance(FileStoreController.class);
 
    /**
     * @Description 上傳臨時文件
     * @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("臨時文件上傳失敗!文件名不符合規范...");
            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 網盤的文件上傳
     * @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("用戶沒有上傳文件的權限!上傳失敗...");
            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 刪除文件
     * @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){
        //獲得文件信息
        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 刪除文件夾並清空文件
     * @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);
        //強制刪除
        deleteFolderF(folder);
        return folder.getParentFolderId() == 0?"redirect:/files":"redirect:/files?fId="+folder.getParentFolderId();
    } 
 
    /**
     * @Description 迭代刪除文件夾裡面的所有文件和子文件夾
     * @Author xw
     * @Date 9:17 2020/2/29
     * @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 添加文件夾
     * @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) {
        //設置文件夾信息
        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 重命名文件夾
     * @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) {
        //獲得文件夾的數據庫信息
        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 重命名文件
     * @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("修改文件名成功!原文件名:"+oldName+"  新文件名:"+newName);
                    }else{
                        logger.error("修改文件名失敗!原文件名:"+oldName+"  新文件名:"+newName);
                    }
                }
            }
        }
        return "redirect:/files?fId="+myFile.getParentFolderId();
    }
 
    /**
     * @Description 獲得二維碼 
     * @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()){
                        //文件不存在,開始生成二維碼並保存文件
                        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 分享文件
     * @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("下載分享文件失敗,參數錯誤");
            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 正則驗證文件名是否合法 [漢字,字符,數字,下劃線,英文句號,橫線]
     * @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 判斷當前瀏覽器是否為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;
    }
 
}

登錄控制器: 

/**
 * @Description 登錄控制器
 * @return
 **/
@Controller
public class LoginController extends BaseController {
 
    private Logger logger = LogUtils.getInstance(LoginController.class);
 
    /**
     * @Description 免登陸用戶入口,用於本地開發測試,上線運營為瞭安全請刪除此方法
     * @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("使用免登陸方式登錄成功!"+user);
        session.setAttribute("loginUser", user);
        return "redirect:/index";
    }
 
    /**
     * 用於註冊流程,用戶名,密碼,郵箱等校驗工作由前端來完成
     *
     * @param map 用於存儲提示信息
     * @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", "驗證碼錯誤");
            return "index";
        }
        // 用戶名去空格
        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("註冊用戶成功!當前註冊用戶" + user);
            logger.info("註冊倉庫成功!當前註冊倉庫" + store);
        } else {
            map.put("errorMsg", "服務器發生錯誤,註冊失敗");
            return "index";
        }
        session.removeAttribute(user.getEmail() + "_code");
        session.setAttribute("loginUser", user);
        return "redirect:/index";
    }
 
    /**
     * 用戶登錄
     * @param map 存儲提示信息
     * @return java.lang.String
     * @author 莫提
     * @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("登錄成功!"+userByEmail);
            return "redirect:/index";
        }else{
            User user1 = userService.getUserByEmail(user.getEmail());
            String errorMsg = user1 == null ? "該郵箱尚未註冊" : "密碼錯誤";
            logger.info("登錄失敗!請確認郵箱和密碼是否正確!");
            //登錄失敗,將失敗信息返回前端渲染
            map.put("errorMsg", errorMsg);
            return "index";
        }
    }
 
    /**
     * @return void
     * @Description 向註冊郵箱發送驗證碼, 並驗證郵箱是否已使用
     * @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("發送驗證碼失敗!郵箱已被註冊!");
            return "exitEmail";
        }
        logger.info("開始發送郵件.../n" + "獲取的到郵件發送對象為:" + mailSender);
        mailUtils = new MailUtils(mailSender);
        String code = "123456";
        session.setAttribute(email + "_code", code);
        return "success";
    }
 
    /**
     * @Description 請求QQ登錄
     * @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("請求QQ登錄,開始跳轉...");
        } catch (QQConnectException | IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * @Description QQ登錄回調地址
     * @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("登錄失敗:沒有獲取到響應參數");
                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));
                // 利用獲取到的accessToken 去獲取當前用的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("用戶的OPEN_ID: " + openID);
                    logger.info("用戶的昵稱: " + removeNonBmpUnicode(userInfoBean.getNickname()));
                    logger.info("用戶的頭像URI: " + userInfoBean.getAvatar().getAvatarURL100());
                    //設置用戶信息
                    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("註冊用戶成功!當前註冊用戶" + user);
                            FileStore store = FileStore.builder().userId(user.getUserId()).build();
                            if (fileStoreService.addFileStore(store) == 1){
                                user.setFileStoreId(store.getFileStoreId());
                                userService.update(user);
                                logger.info("註冊倉庫成功!當前註冊倉庫" + store);
                            }
                        } else {
                            logger.error("註冊用戶失敗!");
                        }
                    }else {
                        user.setUserName(removeNonBmpUnicode(userInfoBean.getNickname()));
                        user.setImagePath(userInfoBean.getAvatar().getAvatarURL100());
                        userService.update(user);
                    }
                    logger.info("QQ用戶登錄成功!"+user);
                    session.setAttribute("loginUser", user);
                    return "redirect:/index";
                } else {
                    logger.error("很抱歉,我們沒能正確獲取到您的信息,原因是: " + userInfoBean.getMsg());
                }
            }
        } catch (QQConnectException e) {
        } finally {
            logger.error("登錄成功!");
        }
        return "登錄失敗!請查看日志信息...";
    }
 
    /**
     * @Description 處理掉QQ網名中的特殊表情
     * @Author xw
     * @Date 18:26 2020/2/25
     * @Param [str]
     * @return java.lang.String 返回處理之後的網名
     **/
    public String removeNonBmpUnicode(String str) {
        if (str == null) {
            return null;
        }
        str = str.replaceAll("[^\\u0000-\\uFFFF]", "");
        if ("".equals(str)) {
            str = "($ _ $)";
        }
        return str;
    }
 
    /**
     * @Description 退出登錄,清空session
     * @Author xw
     * @Date 18:26 2020/2/25
     * @Param []
     * @return java.lang.String
     **/
    @GetMapping("/logout")
    public String logout() {
        logger.info("用戶退出登錄!");
        session.invalidate();
        return "redirect:/";
    }
 
}

系統頁面跳轉控制器:

/**
 * @ClassName: SystemController
 * @Description: 系統頁面跳轉控制器
 **/
@Controller
public class SystemController extends BaseController {
 
    Logger logger = LogUtils.getInstance(SystemController.class);
 
    /**
     * @return java.lang.String
     * @Description 前往我的網盤
     * @Author xw
     * @Date 23:28 2020/2/10
     * @Param [fId, fName, error, map]
     **/
    @GetMapping("/files")
    public String toFileStorePage(Integer fId, String fName, Integer error, Map<String, Object> map) {
        //判斷是否包含錯誤信息
        if (error != null) {
            if (error == 1) {
                map.put("error", "添加失敗!當前已存在同名文件夾");
            }
            if (error == 2) {
                map.put("error", "重命名失敗!文件夾已存在");
            }
        }
        //包含的子文件夾
        List<FileFolder> folders = null;
        //包含的文件
        List<MyFile> files = null;
        //當前文件夾信息
        FileFolder nowFolder = null;
        //當前文件夾的相對路徑
        List<FileFolder> location = new ArrayList<>();
        if (fId == null || fId <= 0) {
            //代表當前為根目錄
            fId = 0;
            folders = fileFolderService.getRootFoldersByFileStoreId(loginUser.getFileStoreId());
            files = myFileService.getRootFilesByFileStoreId(loginUser.getFileStoreId());
            nowFolder = FileFolder.builder().fileFolderId(fId).build();
            location.add(nowFolder);
        } else {
            //當前為具體目錄,訪問的文件夾不是當前登錄用戶所創建的文件夾
            FileFolder folder = fileFolderService.getFileFolderByFileFolderId(fId);
            if (folder.getFileStoreId() - loginUser.getFileStoreId() != 0){
                return "redirect:/error401Page";
            }
            //當前為具體目錄,訪問的文件夾是當前登錄用戶所創建的文件夾
            folders = fileFolderService.getFileFolderByParentFolderId(fId);
            files = myFileService.getFilesByParentFolderId(fId);
            nowFolder = fileFolderService.getFileFolderByFileFolderId(fId);
            //遍歷查詢當前目錄
            FileFolder temp = nowFolder;
            while (temp.getParentFolderId() != 0) {
                temp = fileFolderService.getFileFolderByFileFolderId(temp.getParentFolderId());
                location.add(temp);
            }
        }
        Collections.reverse(location);
        //獲得統計信息
        FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId());
        map.put("statistics", statistics);
        map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission());
        map.put("folders", folders);
        map.put("files", files);
        map.put("nowFolder", nowFolder);
        map.put("location", location);
        logger.info("網盤頁面域中的數據:" + map);
        return "u-admin/files";
    }
 
    /**
     * @Description 前往文件上傳頁面
     * @Author xw
     * @Date 15:16 2020/2/26
     * @Param [fId, fName, map]
     * @return java.lang.String
     **/
    @GetMapping("/upload")
    public String toUploadPage(Integer fId, String fName, Map<String, Object> map) {
        //包含的子文件夾
        List<FileFolder> folders = null;
        //當前文件夾信息
        FileFolder nowFolder = null;
        //當前文件夾的相對路徑
        List<FileFolder> location = new ArrayList<>();
        if (fId == null || fId <= 0) {
            //代表當前為根目錄
            fId = 0;
            folders = fileFolderService.getRootFoldersByFileStoreId(loginUser.getFileStoreId());
            nowFolder = FileFolder.builder().fileFolderId(fId).build();
            location.add(nowFolder);
        } else {
            //當前為具體目錄
            folders = fileFolderService.getFileFolderByParentFolderId(fId);
            nowFolder = fileFolderService.getFileFolderByFileFolderId(fId);
            //遍歷查詢當前目錄
            FileFolder temp = nowFolder;
            while (temp.getParentFolderId() != 0) {
                temp = fileFolderService.getFileFolderByFileFolderId(temp.getParentFolderId());
                location.add(temp);
            }
        }
        Collections.reverse(location);
        //獲得統計信息
        FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId());
        map.put("statistics", statistics);
        map.put("folders", folders);
        map.put("nowFolder", nowFolder);
        map.put("location", location);
        logger.info("網盤頁面域中的數據:" + map);
        return "u-admin/upload";
    }
 
    /**
     * @Description 前往所有文檔頁面
     * @Author xw
     * @Date 10:26 2020/2/26
     * @Param [map]
     * @return java.lang.String
     **/
    @GetMapping("/doc-files")
    public String toDocFilePage( Map<String, Object> map) {
        List<MyFile> files = myFileService.getFilesByType(loginUser.getFileStoreId(),1);
        //獲得統計信息
        FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId());
        map.put("statistics", statistics);
        map.put("files", files);
        map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission());
        return "u-admin/doc-files";
    }
 
    /**
     * @Description 前往所有圖像頁面
     * @Author xw
     * @Date 10:26 2020/2/26
     * @Param [map]
     * @return java.lang.String
     **/
    @GetMapping("/image-files")
    public String toImageFilePage( Map<String, Object> map) {
        List<MyFile> files = myFileService.getFilesByType(loginUser.getFileStoreId(),2);
        //獲得統計信息
        FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId());
        map.put("statistics", statistics);
        map.put("files", files);
        map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission());
        return "u-admin/image-files";
    }
 
    /**
     * @Description 前往所有視頻頁面
     * @Author xw
     * @Date 10:26 2020/2/26
     * @Param [map]
     * @return java.lang.String
     **/
    @GetMapping("/video-files")
    public String toVideoFilePage( Map<String, Object> map) {
        List<MyFile> files = myFileService.getFilesByType(loginUser.getFileStoreId(),3);
        //獲得統計信息
        FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId());
        map.put("statistics", statistics);
        map.put("files", files);
        map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission());
        return "u-admin/video-files";
    }
 
    /**
     * @Description 前往所有音頻頁面
     * @Author xw
     * @Date 10:26 2020/2/26
     * @Param [map]
     * @return java.lang.String
     **/
    @GetMapping("/music-files")
    public String toMusicFilePage( Map<String, Object> map) {
        List<MyFile> files = myFileService.getFilesByType(loginUser.getFileStoreId(),4);
        //獲得統計信息
        FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId());
        map.put("statistics", statistics);
        map.put("files", files);
        map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission());
        return "u-admin/music-files";
    }
 
    /**
     * @Description 前往其他文件頁面
     * @Author xw
     * @Date 10:26 2020/2/26
     * @Param [map]
     * @return java.lang.String
     **/
    @GetMapping("/other-files")
    public String toOtherFilePage( Map<String, Object> map) {
        List<MyFile> files = myFileService.getFilesByType(loginUser.getFileStoreId(),5);
        //獲得統計信息
        FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId());
        map.put("statistics", statistics);
        map.put("files", files);
        map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission());
        return "u-admin/other-files";
    }
 
    /**
     * @Description 登錄之後的用戶主頁
     * @Author xw
     * @Date 10:28 2020/2/26
     * @Param [map]
     * @return java.lang.String
     **/
    @GetMapping("/index")
    public String index(Map<String, Object> map) {
        //獲得統計信息
        FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId());
        statistics.setFileStore(fileStoreService.getFileStoreById(loginUser.getFileStoreId()));
        map.put("statistics", statistics);
        return "u-admin/index";
    }
 
    /**
     * @Description 前往幫助頁面
     * @Author xw
     * @Date 15:17 2020/2/26
     * @Param [map]
     * @return java.lang.String
     **/
    @GetMapping("/help")
    public String helpPage(Map<String, Object> map) {
        //獲得統計信息
        FileStoreStatistics statistics = myFileService.getCountStatistics(loginUser.getFileStoreId());
        map.put("statistics", statistics);
        return "u-admin/help";
    }
}

到此這篇關於Java畢業設計實戰之在線網盤系統的實現的文章就介紹到這瞭,更多相關Java 在線網盤系統內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: