基于javaweb+mysql的springboot+jpa网盘系统设计和实现(javaweb+springboot+ssm+jpa+thymeleaf+html)
运行环境
Java≥8、MySQL≥5.7
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的SpringBoot+JPA网盘系统设计和实现(javaweb+springboot+ssm+jpa+thymeleaf+html)
很多同学都有自己的网盘,方便存储一些java学习教程。该毕业设计实现了一个简易的网盘,包含文件上传和文件分享等功能。 后端技术采用了spring,spring mvc,JPA,前端采用了thymeleaf模板语言。整体业务功能相对不是太复杂,亮点是文件分享功能。
/**
* 文件管理
*
*
*/
@Controller
public class FileController {
public static String fileRootPath;
public static String tempPath; // 分块文件临时存储地址
//MD5文件的大小
public static int size;
private static int secretLen;
// 秘钥
private static String key;
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private IFileService fileService;
@Autowired
private LinkSecretServiceImpl linkSecretService;
@Autowired
private SaveServiceImpl saveService;
@Value("${key}")
public void setKey(String key) {
FileController.key = key;
}
@Value("${tempPath}")
public void setTempPath(String tempPath) {
FileController.tempPath = tempPath;
}
@Value("${fileRootPath}")
public void setFileRootPath(String fileRootPath) {
FileController.fileRootPath = fileRootPath;
}
@Value("${secretLen}")
public void setSecretLen(int secretLen) {
String agent = request.getHeader("user-agent");
String fileName4 = "";
if (agent.contains("Firefox")) {
fileName4 = new String(filename.getBytes(), "iso-8859-1");
} else {
//空格,(,),;,@,#,&,逗号在谷歌浏览器中出现乱码
fileName4 = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20").
replaceAll("%28", "\\(").
replaceAll("%29", "\\)").
replaceAll("%3B", ";").
replaceAll("%40", "@").
replaceAll("%23", "\\#").
replaceAll("%26", "\\&").
replaceAll("%2C", "\\,");
}
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName4 + "\"");
// 循环取出流中的数据
byte[] b = new byte[100];
int len;
try {
while ((len = inStream.read(b)) > 0) {
response.getOutputStream().write(b, 0, len);
}
inStream.close();
responseMsg.setSuccess(true);
} catch (IOException e) {
logger.error("Exception:", e);
responseMsg.setSuccess(false);
}
return responseMsg;
}
}
package com.bjpowernode.pan.controller;
// 登录
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> login(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> map = new HashMap<>();
String userName = request.getParameter("userName");
String password = request.getParameter("password");
String encryptedPwd = "";
try {
//加密的用户密码
encryptedPwd = Md5SaltTool.getEncryptedPwd(password);
logger.warn("encryptedPwd:" + encryptedPwd);
} catch (NoSuchAlgorithmException e) {
logger.error("Exception:", e);
} catch (UnsupportedEncodingException e) {
logger.error("Exception:", e);
}
User dataBaseUser = userService.queryUserByUsername(userName);
if (dataBaseUser != null && encryptedPwd.equals(dataBaseUser.getPassWord())) {
User user = new User(userName, encryptedPwd, dataBaseUser.getLevelType(), dataBaseUser.getEmail(),
dataBaseUser.getPhone(), dataBaseUser.getAlias());
request.getSession().setAttribute("user", user);
logger.info("用户登录成功!");
map.put("result", "1");
map.put("userName", userName);
} else if (dataBaseUser != null && !encryptedPwd.equals(dataBaseUser.getPassWord())) {
logger.info("密码错误!");
map.put("result", "2");
} else {
logger.info("用户不存在!");
map.put("result", "0");
}
return map;
}
// 退出登录
@RequestMapping(value = "/quit", method = RequestMethod.GET)
public String loginOut(HttpServletRequest request) {
if (!SystemUtil.isWindows()) {
// 非windows环境下要删除用户文件
/**
@RequestMapping(value = "/check", method = RequestMethod.POST)
@ResponseBody
public ResponseMsg checkChunk(HttpServletRequest request, HttpServletResponse response) {
ResponseMsg responseMsg = new ResponseMsg();
logger.warn("执行check-------------------");
String fileName = request.getParameter("fileName");
// String fileMd5 = request.getParameter("fileMd5");
String chunk = request.getParameter("chunk");
logger.warn("checkChunk+chunk:" + chunk);
String chunkSize = request.getParameter("chunkSize");
logger.warn("checkChunk+chunkSize:" + chunkSize);
String userName = WebUtil.getUserNameByRequest(request);
logger.warn(tempPath);
String tempDir = FileUtil.getTempDir(tempPath, userName, fileName);
tempDir = StringUtil.stringSlashToOne(tempDir);
File chunkFile = new File(tempDir + "/" + chunk);
boolean result = false;
// 分片文件是否存在,尺寸是否一致
if (chunkFile.exists() && chunkFile.length() == Integer.parseInt(chunkSize)) {
responseMsg.setSuccess(true);
responseMsg.setMsg(chunk);
}
return responseMsg;
}
/**
* 所有分块上传完成后合并
*
* @param request
* @param response
* @param path
*/
@RequestMapping(value = "/merge")
@ResponseBody
public void mergeChunks(HttpServletRequest request, HttpServletResponse response, String path)
throws InterruptedException {
if (path == null) {
return;
}
logger.warn("执行merge");
// 文件下载
@RequestMapping(value = "/download", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsgAdd download(@RequestParam String fileName, String path, HttpServletRequest request) {
if (path == null) {
path = "/";
}
ResponseMsgAdd j = new ResponseMsgAdd();
if (fileName.isEmpty()) {
j.setMsg("文件名字为空!");
return j;
}
// 获取用户名
String userName = WebUtil.getUserNameByRequest(request);
// String userName ="zc";
// 下载文件,获取下载路径,这个是 个映射的路径
String link = fileService.download(fileName, userName, path);
try {
//这里校验要填真实的路经
String newLink = link.replace("/data/", fileRootPath);
String[] md5Array = FileSplit.splitBySizeSubSection(newLink, size,
fileRootPath + "/tempMd5/" + userName + "/");
j.setObj(md5Array);
} catch (Exception e) {
logger.error("Exception:", e);
j.setObj("");
}
if (!link.isEmpty()) {
j.setSuccess(true);
j.setMsg(link);
} else {
j.setMsg("");
logger.warn("下载失败");
}
return j;
}
// 搜索接口
@RequestMapping(value = "/search", produces = "application/json; charset=utf-8")
@ResponseBody
public List<FileMsg> search(@RequestParam String key, String path, HttpServletRequest request) {
if (path == null) {
path = "/";
}
// 获取用户名
String userName = WebUtil.getUserNameByRequest(request);
List<FileMsg> fileMsgList = fileService.search(key, userName, path);
// 判断文件转码情况
for (FileMsg fileMsg : fileMsgList) {
// 跳过文件夹
if (fileMsg.getSize().equals("Directory")) {
continue;
*/
@RequestMapping("upload")
public ResponseMsg upload(@RequestParam String path, HttpServletRequest request) {
try {
// Servlet3.0方式上传文件
Collection<Part> parts = request.getParts();
for (Part part : parts) {
// 忽略路径字段,只处理文件类型
if (part.getContentType() != null) {
String fullPath = root + "sandeepin/" + path;
System.out.println("fullPath:" + fullPath);
File f = new File(fullPath, FileUtil.getFileNameByContentDisposition(part.getHeader("content-disposition")));
if (!FileUtil.writeInputStreamToFile(part.getInputStream(), f)) {
throw new Exception("文件上传失败");
}
}
}
return new ResponseMsg("upload successful!");
} catch (Exception e) {
return new ResponseMsg();
}
}
/**
* 空间占用展示
*
* @param request HttpServletRequest
*/
@GetMapping(value = "/space")
public ResponseMsg getSpaceSize(HttpServletRequest request) {
// 普通用户限制80G,guest用户限制40G,
String userName = WebUtil.getUserNameByRequest(request);
Map<String, String> spaceMap = new HashMap<>(2);
spaceMap.put("totalSpace", "80");
double totalSpace = 80;
if ("guest".equals(userName)) {
spaceMap.put("totalSpace", "40");
totalSpace = 40;
}
long dirlength = SystemUtil.getDirSpaceSize(root + userName);
double dirlengthDouble = dirlength / 1024.0 / 1024 / 1024;
String usedeSpace = String.format("%.2f", dirlengthDouble);
String freeSpace = String.format("%.2f", totalSpace - Double.parseDouble(usedeSpace));
spaceMap.put("freeSpace", freeSpace);
return new ResponseMsg(JSONObject.toJSONString(spaceMap));
}
/**
* 用户文件列表展示
*
* @param path 路径
fileMsg.setTranscode(transcode);
}
// 含有转码文件但没有转码记录,说明之前已完成转码
else {
fileMsg.setTranscode("complete");
}
}
// 没有转码文件说明可转码
else {
fileMsg.setTranscode("transcodable");
}
}
}
return fileMsgList;
}
// 查看单个文件转码状态
@RequestMapping(value = "/transcodestatus", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg transCodeStatus(String path, HttpServletRequest request) {
if (path == null) {
path = "/";
}
logger.warn("transCodeStatus():" + path);
logger.warn("ffmpegTaskMap:" + JSONObject.toJSONString(FfmpegUtil.ffmpegTaskMap));
ResponseMsg responseMsg = new ResponseMsg();
responseMsg.setMsg("noneed");
responseMsg.setSuccess(true);
// 判断文件转码情况
Map<String, Object> map = FfmpegUtil.ffmpegTaskMap.get(path);
if (null != map) {
Boolean transcode = (Boolean) map.get("flag");
if (transcode) {
responseMsg.setMsg("complete");
} else {
responseMsg.setMsg("transcoding");
}
}
return responseMsg;
}
// 文件删除
@RequestMapping(value = "/filedelete", produces = "application/json; charset=utf-8")
@ResponseBody
public String loginOut(HttpServletRequest request) {
if (!SystemUtil.isWindows()) {
// 非windows环境下要删除用户文件
FileUtil.deleteDir(fileRootPath + WebUtil.getUserNameByRequest(request));
}
// 清除session
request.getSession().invalidate();
logger.info("退出登录成功!");
return "login";
}
// 注册
@RequestMapping(value = "/signin", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> signin(@RequestParam(required = false) String alias,
@RequestParam(required = true) String userName, @RequestParam(required = true) String password,
@RequestParam(required = false) String regcode, @RequestParam(required = false) String email,
@RequestParam(required = false) String phone, HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> map = new HashMap<>();
String encryptedPwd = "";
try {
//加密的用户密码
encryptedPwd = Md5SaltTool.getEncryptedPwd(password);
} catch (NoSuchAlgorithmException e) {
logger.error("NoSuchAlgorithmException:", e);
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncodingException:", e);
}
User dataBaseUser = userService.queryUserByUsername(encryptedPwd);
//regcode的重新写入
if (!iVerifyCodeService.isValid(regcode)) {
logger.info("注册失败,激活码失效或不正确!");
map.put("result", "2");
return map;
} else {
if (dataBaseUser == null) {
User user = new User(userName, encryptedPwd, "0", email, phone, alias);
userService.add(user);
logger.info("账号注册成功!");
map.put("result", "1");
} else {
logger.info("用户已经存在,请登录或换一个用户名!");
map.put("result", "0");
}
}
return new ResponseMsg("upload successful!");
} catch (Exception e) {
return new ResponseMsg();
}
}
/**
* 空间占用展示
*
* @param request HttpServletRequest
*/
@GetMapping(value = "/space")
public ResponseMsg getSpaceSize(HttpServletRequest request) {
// 普通用户限制80G,guest用户限制40G,
String userName = WebUtil.getUserNameByRequest(request);
Map<String, String> spaceMap = new HashMap<>(2);
spaceMap.put("totalSpace", "80");
double totalSpace = 80;
if ("guest".equals(userName)) {
spaceMap.put("totalSpace", "40");
totalSpace = 40;
}
long dirlength = SystemUtil.getDirSpaceSize(root + userName);
double dirlengthDouble = dirlength / 1024.0 / 1024 / 1024;
String usedeSpace = String.format("%.2f", dirlengthDouble);
String freeSpace = String.format("%.2f", totalSpace - Double.parseDouble(usedeSpace));
spaceMap.put("freeSpace", freeSpace);
return new ResponseMsg(JSONObject.toJSONString(spaceMap));
}
/**
* 用户文件列表展示
*
* @param path 路径
* @param request HttpServletRequest
* @return List<FileMsg>
*/
@RequestMapping(value = "/list", produces = "application/json; charset=utf-8")
public List<FileMsg> list(String path, HttpServletRequest request) {
String userName = WebUtil.getUserNameByRequest(request);
String fullFilePath = root + userName + "/";
if (path != null) {
fullFilePath += path;
}
return fileService.list(fullFilePath, userName);
}
/**
* 创建目录
*
* @param dirMsg 路径、目录名json体
* @param request HttpServletRequest
}
// 没有转码文件说明可转码
else {
fileMsg.setTranscode("transcodable");
}
}
}
return fileMsgList;
}
// 用户根目录文件列出
@RequestMapping(value = "/userfilelist", produces = "application/json; charset=utf-8")
@ResponseBody
public List<FileMsg> userFileList(@RequestParam(required = false) String key, String path,
HttpServletRequest request) {
if (path == null) {
path = "/";
}
// 获取用户名
String userName = WebUtil.getUserNameByRequest(request);
// 列出用户文件
List<FileMsg> fileMsgList = fileService.userFileList(userName, path);
// 判断文件转码情况
for (FileMsg fileMsg : fileMsgList) {
// 跳过文件夹
if (fileMsg.getSize().equals("Directory")) {
continue;
}
// 正常文件
int suffixidx = (int) StringUtil.getfilesuffix(fileMsg.getName(), true);
String suffix = fileMsg.getName().substring(suffixidx);
if (suffix.equals("mkv") || suffix.equals("rmvb") || suffix.equals("avi") || suffix.equals("wmv")
|| suffix.equals("3gp") || suffix.equals("rm")) {
// 取非文件夹的所有文件名
List<String> namelist = fileMsgList.stream()
.filter(f -> !f.getSize().equals("Directory"))
.map(FileMsg::getName)
.collect(Collectors.toList());
// 含有转码文件的情况下
if (namelist.contains(fileMsg.getName().substring(0, suffixidx) + "mp4")) {
//定位到分享页面
@RequestMapping("/share")
public ModelAndView share(String link, HttpServletRequest request) {
logger.warn("zzc:" + link);
EncryptUtil des = null;
String linkDecoder = "";
try {
des = new EncryptUtil(key, "utf-8");
linkDecoder = des.decode(link);
} catch (Exception e) {
logger.error("Exception:", e);
}
ModelAndView modelAndView = new ModelAndView("share");
modelAndView.addObject("link", link);
modelAndView.addObject("linkDecoder", linkDecoder);
User user = (User) request.getSession().getAttribute("user");
if (user != null) {
modelAndView.addObject("author", user.getUserName());
}
return modelAndView;
}
@RequestMapping("/errorPage")
public ModelAndView errorPage(String message) {
logger.warn("zzc:" + message);
ModelAndView modelAndView = new ModelAndView("errorPage");
modelAndView.addObject("message", message);
return modelAndView;
}
@RequestMapping(value = "/sharefileSecret", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg shareFileSecret(String link, String secret, HttpServletRequest request,
HttpServletResponse response) {
logger.warn("执行sharefileSecret接口");
String downloadLink = "";
Map<Object, String> map = new HashMap<>();
if (!link.isEmpty()) {
// downloadLink= fileService.fileShareCodeDecode(link);
downloadLink = link;
}
}
userService.update(user);
j.setMsg("更新用户信息成功!");
j.setSuccess(true);
return j;
}
//检查是否是登录状态
@RequestMapping(value = "/islogin")
@ResponseBody
public ResponseMsg isLogin(@RequestParam(required = false) String savePath, HttpServletRequest request) {
if (savePath == null) {
savePath = "/";
}
ResponseMsg j = new ResponseMsg();
// 获取用户名
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
//未登录,跳转到登录界面,登录之后默认保存到网盘连接的地址<a href="wut://pan">链接到app</a>
j.setMsg("未登录");
j.setSuccess(false);
} else {
j.setMsg("已登录");
j.setSuccess(true);
}
return j;
}
}
package com.bjpowernode.pan.controller;
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private IFileService fileService;
@Autowired
private LinkSecretServiceImpl linkSecretService;
@Autowired
private SaveServiceImpl saveService;
@Value("${key}")
public void setKey(String key) {
FileController.key = key;
}
@Value("${tempPath}")
public void setTempPath(String tempPath) {
FileController.tempPath = tempPath;
}
@Value("${fileRootPath}")
public void setFileRootPath(String fileRootPath) {
FileController.fileRootPath = fileRootPath;
}
@Value("${secretLen}")
public void setSecretLen(int secretLen) {
FileController.secretLen = secretLen;
}
@Value("${size}")
public void setSize(int size) {
FileController.size = size;
}
// 文件上传
@RequestMapping(value = "/upload", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg upload(@RequestParam MultipartFile file, String path, HttpServletRequest request) {
if (path == null) {
path = "/";
}
ResponseMsg j = new ResponseMsg();
if (file.isEmpty()) {
j.setMsg("请选择要上传的文件!");
return j;
j.setSuccess(true);
j.setMsg("上传成功!");
} else {
j.setMsg("上传失败!");
}
return j;
}
// 文件下载
@RequestMapping(value = "/download", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsgAdd download(@RequestParam String fileName, String path, HttpServletRequest request) {
if (path == null) {
path = "/";
}
ResponseMsgAdd j = new ResponseMsgAdd();
if (fileName.isEmpty()) {
j.setMsg("文件名字为空!");
return j;
}
// 获取用户名
String userName = WebUtil.getUserNameByRequest(request);
// String userName ="zc";
// 下载文件,获取下载路径,这个是 个映射的路径
String link = fileService.download(fileName, userName, path);
try {
//这里校验要填真实的路经
String newLink = link.replace("/data/", fileRootPath);
String[] md5Array = FileSplit.splitBySizeSubSection(newLink, size,
fileRootPath + "/tempMd5/" + userName + "/");
j.setObj(md5Array);
} catch (Exception e) {
logger.error("Exception:", e);
j.setObj("");
}
if (!link.isEmpty()) {
j.setSuccess(true);
j.setMsg(link);
} else {
} else {
if (expireDays != -1) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, expireDays);
Date date = cal.getTime();
linkSecretService.updateExpireDay(linkSecret, date);
linkSecretService.updateShareDate(linkSecret, new Date());
secret = linkSecret.getSecret();
} else {
linkSecretService.updateExpireDay(linkSecret, null);
secret = linkSecret.getSecret();
linkSecretService.updateShareDate(linkSecret, new Date());
}
}
if (SystemUtil.isWindows()) {
b = linkSecret.getSecretLink() + "##" + secret;
} else {
b = b + "##" + secret;
}
if (!"null".equals(b)) {
j.setSuccess(true);
j.setMsg(b);
} else {
j.setMsg("提取码生成失败!");
}
return j;
}
// 文件、文件夹 移动 文件夹移动时fileName=@dir@
@RequestMapping(value = "/filemove", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg fileMove(String fileName, String oldPath, String newPath, HttpServletRequest request) {
if (fileName == null) {
fileName = "@dir@";
}
ResponseMsg j = new ResponseMsg();
if (oldPath.isEmpty() || newPath.isEmpty()) {
j.setMsg("路径名字为空!");
return j;
}
// 获取用户名
String userName = WebUtil.getUserNameByRequest(request);
// 移动文件
boolean b = fileService.userFileDirMove(fileName, oldPath, newPath, userName);
if (b) {
/**
* 主要页面映射
*
*
*/
@Controller
public class IndexController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 管理页面
*
* @return 页面
*/
@RequestMapping("/main")
public ModelAndView admin(HttpServletRequest request) {
User user = (User) request.getSession().getAttribute("user");
String userName = user.getUserName();
ModelAndView modelAndView = new ModelAndView("main");
modelAndView.addObject("author", userName);
return modelAndView;
}
/**
* onlineplayer页面
*
* @return 页面
*/
@RequestMapping("/onlineplayer")
public ModelAndView onlineplayer(HttpServletRequest request, String fileName, String filePath) {
User user = (User) request.getSession().getAttribute("user");
String userName = (user==null)?"null":user.getUserName();
ModelAndView modelAndView = new ModelAndView("onlineplayer");
String tempDir = FileUtil.getTempDir(tempPath, userName, fileName);
tempDir = StringUtil.stringSlashToOne(tempDir);
logger.warn("tempDir:" + tempDir);
File dir = new File(tempDir);
if (!dir.exists()) {
dir.mkdirs();
}
// 创建分片文件并保存
File chunkFile = new File(tempDir + "/" + chunk);
logger.warn(tempDir + "/" + chunk);
try {
chunkFile.createNewFile();
item.transferTo(chunkFile);
} catch (IllegalStateException e) {
logger.warn("保存分片文件出错:" + e.getMessage());
logger.error("Exception:", e);
} catch (IOException e) {
logger.warn("保存分片文件出错:" + e.getMessage());
logger.error("Exception:", e);
}
}
}
}
/**
* 上传之前检查
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/check", method = RequestMethod.POST)
@ResponseBody
public ResponseMsg checkChunk(HttpServletRequest request, HttpServletResponse response) {
ResponseMsg responseMsg = new ResponseMsg();
logger.warn("执行check-------------------");
String fileName = request.getParameter("fileName");
// String fileMd5 = request.getParameter("fileMd5");
String chunk = request.getParameter("chunk");
logger.warn("checkChunk+chunk:" + chunk);
String chunkSize = request.getParameter("chunkSize");
logger.warn("checkChunk+chunkSize:" + chunkSize);
String userName = WebUtil.getUserNameByRequest(request);
logger.warn(tempPath);
String tempDir = FileUtil.getTempDir(tempPath, userName, fileName);
tempDir = StringUtil.stringSlashToOne(tempDir);
File chunkFile = new File(tempDir + "/" + chunk);
boolean result = false;