基于javaweb+mysql的springboot+jpa网盘系统设计和实现(javaweb+springboot+ssm+jpa+thymeleaf+html)
私信源码获取及调试交流
运行环境
Java≥8、MySQL≥5.7
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb的SpringBoot+JPA网盘系统设计和实现(javaweb+springboot+ssm+jpa+thymeleaf+html)
很多同学都有自己的网盘,方便存储一些java学习教程。该毕业设计实现了一个简易的网盘,包含文件上传和文件分享等功能。 后端技术采用了spring,spring mvc,JPA,前端采用了thymeleaf模板语言。整体业务功能相对不是太复杂,亮点是文件分享功能。
} else {
responseMsg.setMsg("transcoding");
}
}
return responseMsg;
}
// 文件删除
@RequestMapping(value = "/filedelete", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg fileDelete(String fileName, String path, HttpServletRequest request) {
if (path == null) {
path = "/";
}
ResponseMsg j = new ResponseMsg();
if (fileName.isEmpty()) {
j.setMsg("文件名字为空!");
return j;
}
// 获取用户名
String userName = WebUtil.getUserNameByRequest(request);
// 删除文件
Boolean[] b = fileService.userFileDelete(fileName, userName, path);
boolean flag = true;
for (int i = 0; i < b.length; i++) {
if (b[i] == false) {
flag = false;
}
}
if (flag) {
j.setSuccess(true);
j.setMsg("删除成功!");
} else {
j.setMsg("删除失败!");
}
return j;
}
// 文件重命名 文件夹重命名时 老名字写path 新名字写newName oldName填@dir@
@RequestMapping(value = "/filerename", produces = "application/json; charset=utf-8")
MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> files = Murequest.getFileMap();
logger.warn("执行前---------");
if (null != files && !files.isEmpty()) {
for (MultipartFile item : files.values()) {
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");
*
* @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;
// 分片文件是否存在,尺寸是否一致
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");
String fileName = request.getParameter("fileName");
logger.warn("mergeChunks+fileName:{}", fileName);
User user = (User) request.getSession().getAttribute("user");
String userName = user.getUserName();
if (path == null) {
path = "/";
}
logger.warn(userName + " " + downloadLink + " " + path);
b = fileService.copyFileToMyPan(userName, downloadLink, path);
responseMsg.setSuccess(b);
if (b == false) {
responseMsg.setMsg("保存失败");
} else {
responseMsg.setMsg("保存成功");
}
}
return responseMsg;
}
/**
* 下载客户端的apk
* filename:下载apk的名字
* downloadPath:下载的文件夹,放在/root/pan/share目录中
*/
@RequestMapping(value = "/downloadApk", produces = {"application/json; charset=UTF-8"})
@ResponseBody
public ResponseMsg shareToMyPan(HttpServletRequest request, HttpServletResponse response, String filename,
String downloadPath) throws FileNotFoundException, UnsupportedEncodingException {
// 读到流中
// String filePath="F:/"+downloadPath+"/"+filename;//window上测试的路径
ResponseMsg responseMsg = new ResponseMsg();
String filePath = fileRootPath + downloadPath + "/" + filename;
InputStream inStream = new FileInputStream(filePath);
if (!new File(filePath).exists()) {
responseMsg.setMsg("找不到文件");
}
// 设置输出的格式
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) {
//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 map;
}
}
@RequestMapping(value = "/username", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg fileRename(HttpServletRequest request) {
ResponseMsg j = new ResponseMsg();
// 获取用户名
User user = (User) request.getSession().getAttribute("user");
String userName = user.getUserName();
if (userName == null) {
userName = "null";
}
j.setMsg(userName);
j.setSuccess(true);
return j;
}
@RequestMapping(value = "/getUserByUserName")
@ResponseBody
public User getUserByUserName(HttpServletRequest request) {
User user = (User) request.getSession().getAttribute("user");
return user;
}
//更新当前用户信息
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;
// 分片文件是否存在,尺寸是否一致
if (chunkFile.exists() && chunkFile.length() == Integer.parseInt(chunkSize)) {
responseMsg.setSuccess(true);
responseMsg.setMsg(chunk);
}
return responseMsg;
}
return new ResponseMsg("delete successful.");
}
/**
* 移动文件或目录(批量)
*
* @param msgList 移动前后的名字jsonList
* @param request HttpServletRequest
* @return ResponseMsg
*/
@PutMapping(value = "/move", produces = "application/json; charset=utf-8")
public ResponseMsg move(@RequestBody List<RenameMsg> msgList, HttpServletRequest request) {
String userName = WebUtil.getUserNameByRequest(request);
msgList.forEach(e -> {
String msg = e.getBefore() + " to " + e.getAfter();
logger.warn("move() file:{}", msg);
try {
// todo
FileUtils.forceDelete(new File(root + userName + "/" + msg));
} catch (IOException ex) {
logger.error("delete() IOException! file:{}", msg);
}
});
return new ResponseMsg("move successful.");
}
}
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;
}
//在数据库查找这个链接
LinkSecret linkSecret = linkSecretService.findLinkSecretBysecretLink(downloadLink);
String secret1 = linkSecret.getSecret();
if (secret1.toLowerCase().equals(secret.toLowerCase())) {
linkSecretService.addOneToDownloadNum(linkSecret);
logger.warn("密码正确!");
logger.warn("codeArray[1]路径:" + link);
ResponseMsg responseMsg = new ResponseMsg();
responseMsg.setSuccess(true);
responseMsg.setMsg(link);
return responseMsg;
} else {
logger.warn("密码不正确!");
ResponseMsg responseMsg = new ResponseMsg();
responseMsg.setSuccess(false);
responseMsg.setMsg("密码不正确!");
return responseMsg;
}
}
// 文件提取码生成,当再次分享同一个文件,只更新过期时间
@RequestMapping(value = "/generateShareLink", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg generateShareLink(@RequestParam String expireDay, String fileName, String path,
HttpServletRequest request) {
String expireDayString = expireDay;
int expireDays = 3;
if (expireDayString != null) {
if (expireDayString.equals("永久有效")) {
/**
*/
@Controller
public class ShareController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private LinkSecretServiceImpl linkSecretService;
@Autowired
private FileServiceImpl fileService;
private SaveServiceImpl saveService;
/**
* @param userName userName
* @param password password
*/
@RequestMapping("/alterPassword")
@ResponseBody
public void alterSecret(@RequestParam String userName, @RequestParam String password) {
userService.alterPassword(userName, password);
}
/**
* 根据用户名删除用户,可以直接访问
*
* @param userName userName
*/
@RequestMapping("/deleteUser")
@ResponseBody
public void deleteUser(@RequestParam String[] userName) {
userService.deleteByUsernames(userName);
}
/**
* 用户产生验证码的接口,只有特定用户可以访问
*/
@RequestMapping(value = "/registerCode")
public ModelAndView registerCode(ModelAndView modelAndView, HttpServletRequest request) {
String username = WebUtil.getUserNameByRequest(request);
if ("sandeepin".equals(username) || "cflower".equals(username)) {
modelAndView.setViewName("registerCode");
return modelAndView;
} else {
modelAndView.setViewName("errorPage");
modelAndView.addObject("message", "没有权限生成验证码!");
return modelAndView;
}
}
/**
* 根据操作人的名字和要验证码人的名字来生成注册码
*
* @param customName
* @param request
* @return
*/
@RequestMapping(value = "proRegisterCode", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg proRegisterCode(@RequestParam String customName, HttpServletRequest request) {
String registerCode = PassWordCreate.createPassWord(6);
VerifyCode verifyCode = new VerifyCode();
verifyCode.setState(false);
verifyCode.setRegisterCode(registerCode);
verifyCode.setOperatePerson(WebUtil.getUserNameByRequest(request));
verifyCode.setDate(new Date());
verifyCode.setCustomName(customName);
boolean result = iVerifyCodeService.save(verifyCode);
}
return j;
}
// 文件重命名 文件夹重命名时 老名字写path 新名字写newName oldName填@dir@
@RequestMapping(value = "/filerename", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg fileRename(String oldName, String newName, String path, HttpServletRequest request) {
if (path == null) {
path = "/";
}
ResponseMsg j = new ResponseMsg();
if (oldName.isEmpty() || newName.isEmpty()) {
j.setMsg("文件名字为空!");
return j;
}
// 获取用户名
String userName = WebUtil.getUserNameByRequest(request);
// 重命名文件
boolean b = fileService.userFileRename(oldName, newName, userName, path);
String saveFilePath = fileRootPath + userName + "/" + path;
String oldNameWithPath = saveFilePath + "/" + oldName;
File file = new File(oldNameWithPath);
if (b) {
j.setSuccess(true);
j.setMsg("重命名成功!");
logger.warn(j.getMsg());
} else if (!file.exists()) {
j.setMsg("没有重命名的权限!");
logger.warn(j.getMsg());
} else {
j.setMsg("重命名失败!");
logger.warn(j.getMsg());
}
return j;
}
// 文件夹创建
@RequestMapping(value = "/dircreate", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg dirCreate(String dirName, String path, HttpServletRequest request) {
if (path == null) {
path = "/";
}
ResponseMsg j = new ResponseMsg();
if (dirName.isEmpty() || path.isEmpty()) {
j.setMsg("文件夹名字为空!");
}
if (flag) {
j.setSuccess(true);
j.setMsg("删除成功!");
} else {
j.setMsg("删除失败!");
}
return j;
}
// 文件重命名 文件夹重命名时 老名字写path 新名字写newName oldName填@dir@
@RequestMapping(value = "/filerename", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg fileRename(String oldName, String newName, String path, HttpServletRequest request) {
if (path == null) {
path = "/";
}
ResponseMsg j = new ResponseMsg();
if (oldName.isEmpty() || newName.isEmpty()) {
j.setMsg("文件名字为空!");
return j;
}
// 获取用户名
String userName = WebUtil.getUserNameByRequest(request);
// 重命名文件
boolean b = fileService.userFileRename(oldName, newName, userName, path);
String saveFilePath = fileRootPath + userName + "/" + path;
String oldNameWithPath = saveFilePath + "/" + oldName;
File file = new File(oldNameWithPath);
if (b) {
j.setSuccess(true);
j.setMsg("重命名成功!");
logger.warn(j.getMsg());
} else if (!file.exists()) {
j.setMsg("没有重命名的权限!");
logger.warn(j.getMsg());
} else {
j.setMsg("重命名失败!");
logger.warn(j.getMsg());
}
return j;
}
// 文件夹创建
@RequestMapping(value = "/dircreate", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg dirCreate(String dirName, String path, HttpServletRequest request) {
if (path == null) {
path = "/";
}
/**
* 管理员维护的接口
*/
@Controller
public class AdminController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private IUserService userService;
@Autowired
private IVerifyCodeService iVerifyCodeService;
/**
* 用户修改密码的接口,可以直接访问
*
* @param userName userName
* @param password password
*/
@RequestMapping("/alterPassword")
@ResponseBody
public void alterSecret(@RequestParam String userName, @RequestParam String password) {
userService.alterPassword(userName, password);
}
/**
* 根据用户名删除用户,可以直接访问
*
*
*
*/
public class WebInterceptor implements HandlerInterceptor {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
boolean flag = true;
if (handler instanceof HandlerMethod) {
String ip = request.getRemoteAddr();
long startTime = System.currentTimeMillis();
request.setAttribute("requestStartTime", startTime);
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
logger.warn("用户ip:" + ip + ",访问目标:" + method.getDeclaringClass().getName() + ":" + method.getName());
User user = (User) request.getSession().getAttribute("user");
if (null == user) {
logger.warn("未登录");
response.sendRedirect("toLogin");
flag = false;
} else {
logger.warn("登录的账号:{}", user.getUserName());
flag = true;
}
}
return flag;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
long startTime = (Long) request.getAttribute("requestStartTime");
long endTime = System.currentTimeMillis();
long executeTime = endTime - startTime;
// 打印方法执行时间
if (executeTime > 1000) {
logger.warn(
"[" + method.getDeclaringClass().getName() + "." + method.getName() + "] 执行耗时 : " + executeTime
+ "ms");
} else {
logger.warn("[" + method.getDeclaringClass().getSimpleName() + "." + method.getName() + "] 执行耗时 : "
+ executeTime + "ms");
}
}
}
public ResponseMsg generateShareLink(@RequestParam String expireDay, String fileName, String path,
HttpServletRequest request) {
String expireDayString = expireDay;
int expireDays = 3;
if (expireDayString != null) {
if (expireDayString.equals("永久有效")) {
expireDays = -1;
} else {
expireDays = Integer.parseInt(expireDayString);
}
}
if (path == null) {
path = "/";
}
ResponseMsg j = new ResponseMsg();
if (fileName.isEmpty() || path.isEmpty()) {
j.setMsg("文件夹名字为空!");
return j;
}
// 获取用户名
String userName = WebUtil.getUserNameByRequest(request);
String filePathAndName = userName + "/" + path + "/" + fileName;
filePathAndName = StringUtil.stringSlashToOne(filePathAndName);
logger.warn("filePathAndName:" + filePathAndName);
String b = fileService.fileShareCodeEncode(filePathAndName);
String secret = "";
File file = new File(fileRootPath + "/" + filePathAndName);
String localLink = "/data/share/" + filePathAndName;
//存入数据库
LinkSecret linkSecret = linkSecretService.findLinkSecretByLocalLinkAndUserName(localLink, userName);
if (linkSecret == null) {
//设置提取密码
secret = PassWordCreate.createPassWord(secretLen);
linkSecret = new LinkSecret();
linkSecret.setLocalLink(localLink);
linkSecret.setSecret(secret);
linkSecret.setUserName(userName);
linkSecret.setDownloadNum(0);
linkSecret.setFileName(fileName);
if (expireDays != -1) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, expireDays);
Date date = cal.getTime();
linkSecret.setExpireDate(date);
}
logger.warn("b:" + b);
linkSecret.setSecretLink(b);
linkSecretService.save(linkSecret);
//test
LinkSecret linkSecretTemp = linkSecretService.findLinkSecretByLocalLinkAndUserName(localLink, userName);
logger.warn(linkSecretTemp.getSecretLink());
MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> files = Murequest.getFileMap();
logger.warn("执行前---------");
if (null != files && !files.isEmpty()) {
for (MultipartFile item : files.values()) {
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) {
String fullFilePath = root + userName + "/";
if (path != null) {
fullFilePath += path;
}
return fileService.list(fullFilePath, userName);
}
/**
* 创建目录
*
* @param dirMsg 路径、目录名json体
* @param request HttpServletRequest
* @return ResponseMsg
*/
@PostMapping(value = "/newdir", produces = "application/json; charset=utf-8")
public ResponseMsg newDir(@RequestBody DirMsg dirMsg, HttpServletRequest request) {
String userName = WebUtil.getUserNameByRequest(request);
String newDir = dirMsg.getPath() + "/" + dirMsg.getName();
logger.warn("newDir() newDir:{}", newDir);
try {
FileUtils.forceMkdir(new File(root + userName + "/" + newDir));
} catch (IOException e) {
logger.error("newDir() IOException! newDir:{}", newDir);
}
return new ResponseMsg(dirMsg.getPath() + "/" + dirMsg.getName());
}
/**
* 重命名文件或目录
*
* @param renameMsg 路径、目录名json体
* @param request HttpServletRequest
* @return ResponseMsg
*/
@PutMapping(value = "/rename", produces = "application/json; charset=utf-8")
public ResponseMsg rename(@RequestBody RenameMsg renameMsg, HttpServletRequest request) {
String userName = WebUtil.getUserNameByRequest(request);
logger.warn("oldName:{} newName:{}", renameMsg.getBefore(), renameMsg.getAfter());
File oldName = new File(root + userName + "/" + renameMsg.getBefore());
File newName = new File(root + userName + "/" + renameMsg.getAfter());
logger.warn("重命名文件");
if (oldName.renameTo(newName)) {
logger.warn("已重命名");
} else {
logger.error("rename Error.");
}
return new ResponseMsg(renameMsg.getAfter());
}
/**
* 删除文件或目录(批量)
*
* @param dirMsgList 路径、目录名jsonList
* @param request HttpServletRequest