基于jeecgboot的个人网盘功能开发(三)

简介: 基于jeecgboot的个人网盘功能开发(三)

    今天主要是讲网盘功能的后端部分。

     后端主要包括文件目录的相关操作以及一些文件的在线操作。

    1、文件的上传

    目前支持本地,minio与阿里云的oss文件上传,当然也可以扩充到其它存储的上传。

@Override
  public void uploadFile(HttpServletRequest request, UploadFileDTO uploadFileDto, String userId) {
    UploadFile uploadFile = new UploadFile();
        uploadFile.setChunkNumber(uploadFileDto.getChunkNumber());
        uploadFile.setChunkSize(uploadFileDto.getChunkSize());
        uploadFile.setTotalChunks(uploadFileDto.getTotalChunks());
        uploadFile.setIdentifier(uploadFileDto.getIdentifier());
        uploadFile.setTotalSize(uploadFileDto.getTotalSize());
        uploadFile.setCurrentChunkSize(uploadFileDto.getCurrentChunkSize());
        Uploader uploader = ndFactory.getUploader();
        if (uploader == null) {
            log.error("上传失败,请检查storageType是否配置正确");
            throw new UploadException("上传失败");
        }
        List<UploadFileResult> uploadFileResultList;
        try {
            uploadFileResultList = uploader.upload(request, uploadFile);
        } catch (Exception e) {
            log.error("上传失败,请检查NBCIO上传连接配置是否正确");
            throw new UploadException("上传失败", e);
        }
        for (int i = 0; i < uploadFileResultList.size(); i++){
            UploadFileResult uploadFileResult = uploadFileResultList.get(i);
            String relativePath = uploadFileDto.getRelativePath();
            EstarFile estarFile = null;
            if (relativePath.contains("/")) {
                estarFile = new EstarFile(uploadFileDto.getFilePath(), relativePath, false);
            } else {
                estarFile = new EstarFile(uploadFileDto.getFilePath(), uploadFileDto.getFilename(), false);
            }
            if (UploadFileStatusEnum.SUCCESS.equals(uploadFileResult.getStatus())){
              NdFile ndFile = new NdFile(uploadFileResult);
              ndFile.setCreateBy(userId);
                fileMapper.insert(ndFile);
                NdUserfile userFile = new NdUserfile(estarFile, userId, ndFile.getId());
                NdUserfile param = NdFileUtil.searchQiwenFileParam(userFile);
                List<NdUserfile> userFileList = userFileMapper.selectList(new QueryWrapper<>(param));
                if (userFileList.size() > 0) {
                    String fileName = fileDealComp.getRepeatFileName(userFile, userFile.getFilepath());
                    userFile.setFilename(fileName);
                }
                userFileMapper.insert(userFile);
                if (relativePath.contains("/")) {
                    fileDealComp.restoreParentFilePath(estarFile, userId);
                }
                fileDealComp.uploadESByUserFileId(userFile.getId());
                LambdaQueryWrapper<NdUploadtaskdetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(NdUploadtaskdetail::getIdentifier, uploadFileDto.getIdentifier());
                uploadTaskDetailMapper.delete(lambdaQueryWrapper);
                LambdaUpdateWrapper<NdUploadtask> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.set(NdUploadtask::getUploadstatus, UploadFileStatusEnum.SUCCESS.getCode())
                        .eq(NdUploadtask::getIdentifier, uploadFileDto.getIdentifier());
                uploadTaskMapper.update(null, lambdaUpdateWrapper);
                try {
                    if (EstarUtils.isImageFile(uploadFileResult.getExtendName())) {
                        BufferedImage src = uploadFileResult.getBufferedImage();
                        NdImage image = new NdImage();
                        image.setImagewidth(src.getWidth());
                        image.setImageheight(src.getHeight());
                        image.setFileid(ndFile.getId());
                        imageMapper.insert(image);
                    }
                } catch (Exception e) {
                    log.error("生成图片缩略图失败!", e);
                }
                fileDealComp.parseMusicFile(uploadFileResult.getExtendName(), uploadFileResult.getStorageType().getName(), uploadFileResult.getFileUrl(), ndFile.getId());
            } else if (UploadFileStatusEnum.UNCOMPLATE.equals(uploadFileResult.getStatus())) {
              NdUploadtaskdetail uploadTaskDetail = new NdUploadtaskdetail();
                uploadTaskDetail.setFilepath(estarFile.getParent());
                uploadTaskDetail.setFilename(estarFile.getNameNotExtend());
                uploadTaskDetail.setChunknumber(uploadFileDto.getChunkNumber());
                uploadTaskDetail.setChunksize((int)uploadFileDto.getChunkSize());
                uploadTaskDetail.setRelativepath(uploadFileDto.getRelativePath());
                uploadTaskDetail.setTotalchunks(uploadFileDto.getTotalChunks());
                uploadTaskDetail.setTotalsize((int)uploadFileDto.getTotalSize());
                uploadTaskDetail.setIdentifier(uploadFileDto.getIdentifier());
                uploadTaskDetailMapper.insert(uploadTaskDetail);
            } else if (UploadFileStatusEnum.FAIL.equals(uploadFileResult.getStatus())) {
                LambdaQueryWrapper<NdUploadtaskdetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(NdUploadtaskdetail::getIdentifier, uploadFileDto.getIdentifier());
                uploadTaskDetailMapper.delete(lambdaQueryWrapper);
                LambdaUpdateWrapper<NdUploadtask> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.set(NdUploadtask::getUploadstatus, UploadFileStatusEnum.FAIL.getCode())
                        .eq(NdUploadtask::getIdentifier, uploadFileDto.getIdentifier());
                uploadTaskMapper.update(null, lambdaUpdateWrapper);
            }
        }
    
  }

    这里给出一个minio上传例子代码

protected UploadFileResult doUploadFlow(EstarMultipartFile estarMultipartFile, UploadFile uploadFile) {
        UploadFileResult uploadFileResult = new UploadFileResult();
        try {
            estarMultipartFile.getFileUrl(uploadFile.getIdentifier());
            String fileUrl = EstarUtils.getUploadFileUrl(uploadFile.getIdentifier(), estarMultipartFile.getExtendName());
            File tempFile =  EstarUtils.getTempFile(fileUrl);
            File processFile = EstarUtils.getProcessFile(fileUrl);
            byte[] fileData = estarMultipartFile.getUploadBytes();
            writeByteDataToFile(fileData, tempFile, uploadFile);
            //判断是否完成文件的传输并进行校验与重命名
            boolean isComplete = checkUploadStatus(uploadFile, processFile);
            uploadFileResult.setFileUrl(fileUrl);
            uploadFileResult.setFileName(estarMultipartFile.getFileName());
            uploadFileResult.setExtendName(estarMultipartFile.getExtendName());
            uploadFileResult.setFileSize(uploadFile.getTotalSize());
            uploadFileResult.setStorageType(StorageTypeEnum.MINIO);
            if (uploadFile.getTotalChunks() == 1) {
                uploadFileResult.setFileSize(estarMultipartFile.getSize());
            }
            uploadFileResult.setIdentifier(uploadFile.getIdentifier());
            if (isComplete) {
                minioUpload(fileUrl, tempFile, uploadFile);
                uploadFileResult.setFileUrl(fileUrl);
                tempFile.delete();
                if (EstarUtils.isImageFile(uploadFileResult.getExtendName())) {
                    InputStream inputStream = null;
                    try {
                      
                      MinioClient minioClient = MinioUtil.getMinioClient();
                        inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(minioConfig.getBucketName()).object(uploadFileResult.getFileUrl()).build());
                        BufferedImage src  = ImageIO.read(inputStream);
                        uploadFileResult.setBufferedImage(src);
                    } catch (IOException | InternalException | XmlParserException | InvalidResponseException | InvalidKeyException | NoSuchAlgorithmException | ErrorResponseException | InsufficientDataException | ServerException e) {
                        e.printStackTrace();
                    } finally {
                        IOUtils.closeQuietly(inputStream);
                    }
                }
                uploadFileResult.setStatus(UploadFileStatusEnum.SUCCESS);
            } else {
                uploadFileResult.setStatus(UploadFileStatusEnum.UNCOMPLATE);
            }
        } catch (IOException e) {
            throw new UploadException(e);
        }
        return uploadFileResult;
    }

2、文件的分享

public ShareFileVO shareFile(ShareFileDTO shareSecretDTO) {
    ShareFileVO shareSecretVO = new ShareFileVO();
    SysUser loginUser = iEstarThirdService.getLoginUser();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        NdShare share = new NdShare();
        BeanUtil.copyProperties(shareSecretDTO, share);
        share.setCreateTime(new Date());
        share.setCreateBy(loginUser.getUsername());
        share.setSharestatus(0);
        if (shareSecretDTO.getSharetype() == 1) {
            String extractionCode = RandomUtil.randomNumbers(6);
            share.setExtractioncode(extractionCode);
            shareSecretVO.setExtractionCode(share.getExtractioncode());
        }
        share.setSharebatchnum(uuid);
        shareService.save(share);
        List<NdSharefile> fileList = JSON.parseArray(shareSecretDTO.getFiles(), NdSharefile.class);
        List<NdSharefile> saveFileList = new ArrayList<>();
        for (NdSharefile shareFile : fileList) {
          NdUserfile userFile = userFileService.getById(shareFile.getUserfileid());
            if (userFile.getCreateBy().compareTo(loginUser.getUsername()) != 0) {
              Result.error("您只能分享自己的文件");
                return null;
            }
            if (userFile.getIsdir() == 1) {
              EstarFile estarFile = new EstarFile(userFile.getFilepath(), userFile.getFilename(), true);
                List<NdUserfile> userfileList = userFileService.selectUserFileByLikeRightFilePath(estarFile.getPath(), loginUser.getUsername());
                for (NdUserfile userFile1 : userfileList) {
                  NdSharefile shareFile1 = new NdSharefile();
                    shareFile1.setUserfileid(userFile1.getId());
                    shareFile1.setSharebatchnum(uuid);
                    shareFile1.setSharefilepath(userFile1.getFilepath().replaceFirst(userFile.getFilepath().equals("/") ? "" : userFile.getFilepath(), ""));
                    saveFileList.add(shareFile1);
                }
            }
            shareFile.setSharefilepath("/");
            shareFile.setSharebatchnum(uuid);
            saveFileList.add(shareFile);
        }
        for (NdSharefile saveFile : saveFileList) {
          shareFileService.save(saveFile);
        }
        shareSecretVO.setShareBatchNum(uuid);
        return shareSecretVO;
  }

3、文件的在线解压

public Result unzipFile(@RequestBody UnzipFileDTO unzipFileDto) {
    try {
      String userFileId = unzipFileDto.getUserFileId();
      int unzipMode = unzipFileDto.getUnzipMode();
      String filePath = unzipFileDto.getFilePath();
      NdUserfile userFile = userFileMapper.selectById(userFileId);
      NdFile ndFile = fileMapper.selectById(userFile.getFileid());
          File destFile = new File(EstarUtils.getStaticPath() + "temp" + File.separator + ndFile.getFileurl());
          Downloader downloader = ufopFactory.getDownloader(ndFile.getStoragetype());
          DownloadFile downloadFile = new DownloadFile();
          downloadFile.setFileUrl(ndFile.getFileurl());
          InputStream inputStream = downloader.getInputStream(downloadFile);
          try {
              FileUtils.copyInputStreamToFile(inputStream, destFile);
          } catch (IOException e) {
              e.printStackTrace();
          }
          String extendName = userFile.getExtendname();
          String unzipUrl = EstarUtils.getTempFile(ndFile.getFileurl()).getAbsolutePath().replace("." + extendName, "");
          List<String> fileEntryNameList = new ArrayList<>();
          try {
              fileEntryNameList = FileOperation.unzip(destFile, unzipUrl);
          } catch (Exception e) {
              e.printStackTrace();
              log.error("解压失败" + e);
              throw new EstarException(500001, "解压异常:" + e.getMessage());
          }
          if (destFile.exists()) {
              destFile.delete();
          }
          if (!fileEntryNameList.isEmpty() && unzipMode == 1) {
            NdUserfile estarDir = NdFileUtil.getQiwenDir(userFile.getCreateBy(), userFile.getFilepath(), userFile.getFilename());
              userFileMapper.insert(estarDir);
          }
          for (int i = 0; i < fileEntryNameList.size(); i++){
              String entryName = fileEntryNameList.get(i);
              asyncTaskComp.saveUnzipFile(userFile, ndFile, unzipMode, entryName, filePath);
          }
        } catch (EstarException e) {
            return Result.error(e.getMessage());
        }
        return Result.OK("解压成功");
    }

4、文件的下载

public void downloadFile(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
      DownloadFileDTO downloadFileDTO) {
    Cookie[] cookieArr = httpServletRequest.getCookies();
        String token = "";
        if (StringUtils.isNotEmpty(downloadFileDTO.getToken())) {
            token = downloadFileDTO.getToken();
        } else {
          if (cookieArr != null) {
              for (Cookie cookie : cookieArr) {
                  if ("token".equals(cookie.getName())) {
                      token = cookie.getValue();
                  }
              }
          }
        }
        boolean authResult = fileDealComp.checkAuthDownloadAndPreview(downloadFileDTO.getShareBatchNum(),
                downloadFileDTO.getExtractionCode(),
                token,
                downloadFileDTO.getUserFileId(), null);
        if (!authResult) {
            log.error("没有权限下载!!!");
            return;
        }
        httpServletResponse.setContentType("application/force-download");// 设置强制下载不打开
        NdUserfile userFile = userFileMapper.selectById(downloadFileDTO.getUserFileId());
        String fileName = "";
        if (userFile.getIsdir() == 1) {
            fileName = userFile.getFilename() + ".zip";
        } else {
            fileName = userFile.getFilename() + "." + userFile.getExtendname();
        }
        try {
            fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        httpServletResponse.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
        if (userFile.isFile()) {
          NdFile ndFile = fileMapper.selectById(userFile.getFileid());
            Downloader downloader = ndFactory.getDownloader(ndFile.getStoragetype());
            if (downloader == null) {
                log.error("下载失败,文件存储类型不支持下载,storageType:{}", ndFile.getStoragetype());
                throw new DownloadException("下载失败");
            }
            DownloadFile downloadFile = new DownloadFile();
            downloadFile.setFileUrl(ndFile.getFileurl());
            httpServletResponse.setContentLengthLong(ndFile.getFilesize());
            downloader.download(httpServletResponse, downloadFile);
        } else {
          EstarFile estarFile = new EstarFile(userFile.getFilepath(), userFile.getFilename(), true);
            List<NdUserfile> userFileList = userFileMapper.selectUserFileByLikeRightFilePath(estarFile.getPath() , userFile.getCreateBy());
            List<String> userFileIds = userFileList.stream().map(NdUserfile::getId).collect(Collectors.toList());
            downloadUserFileList(httpServletResponse, userFile.getFilepath(), userFile.getFilename(), userFileIds);
        }
    
  }

5、文件的移动

public String moveFile(MoveFileDTO moveFileDto) {
    SysUser loginUser = iEstarThirdService.getLoginUser();
        String userId = loginUser.getUsername();
    NdUserfile userFile = userFileService.getById(moveFileDto.getUserFileId());
        String oldfilePath = userFile.getFilepath();
        String newfilePath = moveFileDto.getFilePath();
        String fileName = userFile.getFilename();
        String extendName = userFile.getExtendname();
        if (StringUtils.isEmpty(extendName)) {
          EstarFile estarFile = new EstarFile(oldfilePath, fileName, true);
            if (newfilePath.startsWith(estarFile.getPath() + EstarFile.separator) || newfilePath.equals(estarFile.getPath())) {
                return "原路径与目标路径冲突,不能移动";
            }
        }
        userFileService.updateFilepathByUserFileId(moveFileDto.getUserFileId(), newfilePath, userId);
        fileDealComp.deleteRepeatSubDirFile(newfilePath, userId);
        return "移动成功";
  }

6、文件的复制

public String copyFile(CopyFileDTO copyFileDTO) {
    SysUser loginUser = iEstarThirdService.getLoginUser();
        String userId = loginUser.getUsername();
    String filePath = copyFileDTO.getFilePath();
        String userFileIds = copyFileDTO.getUserFileIds();
        String[] userFileIdArr = userFileIds.split(",");
        for (String userFileId : userFileIdArr) {
          NdUserfile userFile = userFileService.getById(userFileId);
            String oldfilePath = userFile.getFilepath();
            String fileName = userFile.getFilename();
            if (userFile.isDirectory()) {
                EstarFile estarFile = new EstarFile(oldfilePath, fileName, true);
                if (filePath.startsWith(estarFile.getPath() + EstarFile.separator) || filePath.equals(estarFile.getPath())) {
                    return "原路径与目标路径冲突,不能复制";
                }
            }
            userFileService.userFileCopy(userId, userFileId, filePath);
            fileDealComp.deleteRepeatSubDirFile(filePath, userId);
        }
        return "复制成功";
  }

7、文件的删除

public void deleteUserFile(String userFileId, String userId) {
    SysUser loginUser = iEstarThirdService.getLoginUser();
    NdUserfile userFile = userFileMapper.selectById(userFileId);
        String uuid = UUID.randomUUID().toString();
        if (userFile.getIsdir() == 1) {
            LambdaUpdateWrapper<NdUserfile> userFileLambdaUpdateWrapper = new LambdaUpdateWrapper<NdUserfile>();
            userFileLambdaUpdateWrapper.set(NdUserfile::getDeleteflag, RandomUtil.randomInt(FileConstant.deleteFileRandomSize))
                    .set(NdUserfile::getDeletebatchnum, uuid)
                    .set(NdUserfile::getDeletetime, new Date())
                    .eq(NdUserfile::getId, userFileId);
            userFileMapper.update(null, userFileLambdaUpdateWrapper);
            String filePath = new EstarFile(userFile.getFilepath(), userFile.getFilename(), true).getPath();
            updateFileDeleteStateByFilePath(filePath, uuid, loginUser.getUsername());
        } else {
          NdUserfile userFileTemp = userFileMapper.selectById(userFileId);
            LambdaUpdateWrapper<NdUserfile> userFileLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            userFileLambdaUpdateWrapper.set(NdUserfile::getDeleteflag, RandomUtil.randomInt(1, FileConstant.deleteFileRandomSize))
                    .set(NdUserfile::getDeletetime, new Date())
                    .set(NdUserfile::getDeletebatchnum, uuid)
                    .eq(NdUserfile::getId, userFileTemp.getId());
            userFileMapper.update(null, userFileLambdaUpdateWrapper);
        }
        NdRecoveryfile recoveryFile = new NdRecoveryfile();
        recoveryFile.setUserfileid(userFileId);
        recoveryFile.setDeletetime(new Date());
        recoveryFile.setDeletebatchnum(uuid);
        recoveryFileMapper.insert(recoveryFile);
  }

8、文件的重命名

public String renameFile(RenameFileDTO renameFileDto) {
    SysUser loginUser = iEstarThirdService.getLoginUser();
        String userId = loginUser.getUsername();
    NdUserfile userFile = userFileService.getById(renameFileDto.getUserFileId());
          List<NdUserfile> userFiles = userFileService.selectUserFileByNameAndPath(renameFileDto.getFileName(), userFile.getFilepath(), userId);
          if (userFiles != null && !userFiles.isEmpty()) {
              return "同名文件已存在";
          }
          LambdaUpdateWrapper<NdUserfile> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
          lambdaUpdateWrapper.set(NdUserfile::getFilename, renameFileDto.getFileName())
                  .set(NdUserfile::getCreateTime, new Date())
                  .eq(NdUserfile::getId, renameFileDto.getUserFileId());
          userFileService.update(lambdaUpdateWrapper);
          if (1 == userFile.getIsdir()) {
              List<NdUserfile> list = userFileService.selectUserFileByLikeRightFilePath(new EstarFile(userFile.getFilepath(), userFile.getFilename(), true).getPath(), userId);
              for (NdUserfile newUserFile : list) {
                  newUserFile.setFilepath(newUserFile.getFilepath().replaceFirst(new EstarFile(userFile.getFilepath(), userFile.getFilename(), userFile.getIsdir() == 1).getPath(),
                          new EstarFile(userFile.getFilepath(), renameFileDto.getFileName(), userFile.getIsdir() == 1).getPath()));
                  userFileService.updateById(newUserFile);
              }
          }
          fileDealComp.uploadESByUserFileId(renameFileDto.getUserFileId());
          return "改名成功";
  }

9、文件的详情

public FileDetailVO getFileDetail(String userFileId) {
    NdUserfile userFile = userFileMapper.selectById(userFileId);
    NdFile ndFile = fileMapper.selectById(userFile.getFileid());
        NdMusic music = musicMapper.selectOne(new QueryWrapper<NdMusic>().eq("fileId", userFile.getFileid()));
        NdImage image = imageMapper.selectOne(new QueryWrapper<NdImage>().eq("fileId", userFile.getFileid()));
        if ("mp3".equalsIgnoreCase(userFile.getExtendname()) || "flac".equalsIgnoreCase(userFile.getExtendname())) {
            if (music == null) {
                fileDealComp.parseMusicFile(userFile.getExtendname(), ndFile.getStoragetype(), ndFile.getFileurl(), ndFile.getId());
                music = musicMapper.selectOne(new QueryWrapper<NdMusic>().eq("fileId", userFile.getFileid()));
            }
        }
        FileDetailVO fileDetailVO = new FileDetailVO();
        BeanUtil.copyProperties(userFile, fileDetailVO);
        BeanUtil.copyProperties(ndFile, fileDetailVO);
        fileDetailVO.setMusic(music);
        fileDetailVO.setImage(image);
        return fileDetailVO;
  }

10、文件的预览

public void preview(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
      PreviewDTO previewDTO) {
    if (previewDTO.getPlatform() != null && previewDTO.getPlatform() == 2) {
            previewPictureFile(httpServletResponse, previewDTO);
            return ;
        }
        String token = "";
        if (StringUtils.isNotEmpty(previewDTO.getToken())) {
            token = previewDTO.getToken();
        } else {
            Cookie[] cookieArr = httpServletRequest.getCookies();
            if (cookieArr != null) {
                for (Cookie cookie : cookieArr) {
                    if ("token".equals(cookie.getName())) {
                        token = cookie.getValue();
                    }
                }
            }
        }
        NdUserfile userFile = userFileService. getById(previewDTO.getUserFileId());
        boolean authResult = fileDealComp.checkAuthDownloadAndPreview(previewDTO.getShareBatchNum(),
                previewDTO.getExtractionCode(),
                token,
                previewDTO.getUserFileId(),
                previewDTO.getPlatform());
        if (!authResult) {
            log.error("没有权限预览!!!");
            return;
        }
        String fileName = userFile.getFilename() + "." + userFile.getExtendname();
        try {
            fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        httpServletResponse.addHeader("Content-Disposition", "fileName=" + fileName);// 设置文件名
        String mime = MimeUtils.getMime(userFile.getExtendname());
        httpServletResponse.setHeader("Content-Type", mime);
        if (EstarUtils.isImageFile(userFile.getExtendname())) {
            httpServletResponse.setHeader("cache-control", "public");
        }
        NdFile ndFile = fileService.getById(userFile.getFileid());
        if (EstarUtils.isVideoFile(userFile.getExtendname()) || "mp3".equalsIgnoreCase(userFile.getExtendname()) || "flac".equalsIgnoreCase(userFile.getExtendname())) {
            //获取从那个字节开始读取文件
            String rangeString = httpServletRequest.getHeader("Range");
            int start = 0;
            if (StringUtils.isNotBlank(rangeString)) {
                start = Integer.parseInt(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
            }
            Downloader downloader = ndFactory.getDownloader(ndFile.getStoragetype());
            DownloadFile downloadFile = new DownloadFile();
            downloadFile.setFileUrl(ndFile.getFileurl());
            Range range = new Range();
            range.setStart(start);
            if (start + 1024 * 1024 * 1 >= ndFile.getFilesize().intValue()) {
                range.setLength(ndFile.getFilesize().intValue() - start);
            } else {
                range.setLength(1024 * 1024 * 1);
            }
            downloadFile.setRange(range);
            InputStream inputStream = downloader.getInputStream(downloadFile);
            OutputStream outputStream = null;
      try {
        outputStream = httpServletResponse.getOutputStream();
      } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
            try {
                //返回码需要为206,代表只处理了部分请求,响应了部分数据
                httpServletResponse.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                // 每次请求只返回1MB的视频流
                httpServletResponse.setHeader("Accept-Ranges", "bytes");
                //设置此次相应返回的数据范围
                httpServletResponse.setHeader("Content-Range", "bytes " + start + "-" + (ndFile.getFilesize() - 1) + "/" + ndFile.getFilesize());
                try {
          IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
            } finally {
                IOUtils.closeQuietly(inputStream);
                IOUtils.closeQuietly(outputStream);
                if (downloadFile.getOssClient() != null) {
                    downloadFile.getOssClient().shutdown();
                }
            }
        } else {
            previewFile(httpServletResponse, previewDTO);
        }
    
  }
public void previewFile(HttpServletResponse httpServletResponse, PreviewDTO previewDTO) {
    NdUserfile userFile = userFileMapper.selectById(previewDTO.getUserFileId());
    NdFile ndFile = fileMapper.selectById(userFile.getFileid());
        Previewer previewer = ndFactory.getPreviewer(ndFile.getStoragetype());
        if (previewer == null) {
            log.error("预览失败,文件存储类型不支持预览,storageType:{}", ndFile.getStoragetype());
            throw new UploadException("预览失败");
        }
        PreviewFile previewFile = new PreviewFile();
        previewFile.setFileUrl(ndFile.getFileurl());
        try {
            if ("true".equals(previewDTO.getIsMin())) {
                previewer.imageThumbnailPreview(httpServletResponse, previewFile);
            } else {
                previewer.imageOriginalPreview(httpServletResponse, previewFile);
            }
        } catch (Exception e){
                if (e.getMessage().contains("ClientAbortException")) {
                //该异常忽略不做处理
            } else {
                log.error("预览文件出现异常:{}", e.getMessage());
            }
        }
    
  }

11、文件的恢复

public void restorefile(String deleteBatchNum, String filePath, String username) {
    LambdaUpdateWrapper<NdUserfile> userFileLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        userFileLambdaUpdateWrapper.set(NdUserfile::getDeleteflag, 0)
                .set(NdUserfile::getDeletebatchnum, "")
                .eq(NdUserfile::getDeletebatchnum, deleteBatchNum);
        userFileMapper.update(null, userFileLambdaUpdateWrapper);
        EstarFile estarFile = new EstarFile(filePath, true);
        fileDealComp.restoreParentFilePath(estarFile, username);
        fileDealComp.deleteRepeatSubDirFile(filePath, username);
        // TODO 如果被还原的文件已存在,暂未实现
        LambdaQueryWrapper<NdRecoveryfile> recoveryFileServiceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        recoveryFileServiceLambdaQueryWrapper.eq(NdRecoveryfile::getDeletebatchnum, deleteBatchNum);
        recoveryFileMapper.delete(recoveryFileServiceLambdaQueryWrapper);
  }


相关文章
|
7月前
|
网络协议 Java 网络安全
基于Jeecgboot前后端分离的流程管理平台演示系统安装(一)
基于Jeecgboot前后端分离的流程管理平台演示系统安装(一)
48 1
|
7月前
|
资源调度 前端开发 Java
基于Jeecgboot前后端分离的流程管理平台演示系统安装(二)
基于Jeecgboot前后端分离的流程管理平台演示系统安装(二)
91 1
|
7月前
|
前端开发 数据库
基于jeecgboot的个人网盘功能开发(二)
基于jeecgboot的个人网盘功能开发(二)
59 0
|
安全 数据管理 数据安全/隐私保护
PDS实现企业网盘搭建心得体会
在试用基于PDS实现企业网盘搭建的过程中,我发现这是一个强大而灵活的解决方案,可以满足企业对于数据管理和共享的各种需求
101 2
|
7月前
|
资源调度 前端开发 jenkins
基于Jeecgboot前后端分离的流程管理平台演示系统安装(四)
基于Jeecgboot前后端分离的流程管理平台演示系统安装(四)
63 1
|
7月前
|
前端开发 jenkins Java
基于Jeecgboot前后端分离的流程管理平台演示系统安装(三)
基于Jeecgboot前后端分离的流程管理平台演示系统安装(三)
54 1
|
7月前
|
jenkins 持续交付
基于Jeecgboot前后端分离的流程管理平台演示系统安装(五)
基于Jeecgboot前后端分离的流程管理平台演示系统安装(五)
41 0
基于Jeecgboot前后端分离的流程管理平台演示系统安装(五)
|
供应链 搜索推荐 数据可视化
我用低代码平台,简单搭建了一套管理系统
我用低代码平台,简单搭建了一套管理系统
170 0
|
7月前
|
数据库
基于jeecgboot的个人网盘功能开发(一)
基于jeecgboot的个人网盘功能开发(一)
50 0
|
7月前
|
移动开发 前端开发
基于jeecgboot的个人网盘功能演示系统发布
基于jeecgboot的个人网盘功能演示系统发布
70 0