java 文件上传 删除工具类

谁践踏了优雅 2023-06-28 09:53 36阅读 0赞

1.文件上传

  1. /**
  2. *
  3. * @param file 上传的文件
  4. * @param relPath 真实存储地址
  5. * @param urlPath url隐射地址
  6. * @param loanId 新文件名
  7. * @param request HttpServletRequest
  8. * @return
  9. */
  10. public String uploadPicture(MultipartFile file,String relPath,String urlPath,String loanId,HttpServletRequest request){
  11. try {
  12. if(file==null||loanId==null||loanId=="")
  13. return null;
  14. File targetFile=null;
  15. String url="";//返回存储路径
  16. String fileName=file.getOriginalFilename();//获取文件名加后缀
  17. if(fileName!=null&&fileName!=""){
  18. String returnUrl = request.getScheme() + "://" + request.getServerName() + ":8089" + request.getContextPath() +urlPath+"/";//存储路径
  19. String path = ""; //文件存储位置
  20. // path = "E:\\txt\\loan";
  21. path = relPath;
  22. String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
  23. fileName=loanId+fileF;//新的文件名
  24. //先判断文件是否存在
  25. //获取文件夹路径
  26. File file1 =new File(path);
  27. //如果文件夹不存在则创建
  28. if(!file1 .exists() && !file1 .isDirectory()){
  29. file1 .mkdir();
  30. }
  31. //将图片存入文件夹
  32. targetFile = new File(file1, fileName);
  33. try {
  34. //将上传的文件写到服务器上指定的文件。
  35. file.transferTo(targetFile);
  36. url=returnUrl+fileName;
  37. return url;
  38. } catch (Exception e) {
  39. System.out.println("文件上传错误:"+e.getMessage());
  40. return null;
  41. }
  42. }else {
  43. return null;
  44. }
  45. } catch (Exception e) {
  46. return null;
  47. }
  48. }

2.文件删除

  1. public static boolean delFile(File file) {
  2. if (!file.exists()) {
  3. return false;
  4. }
  5. if (file.isDirectory()) {
  6. File[] files = file.listFiles();
  7. for (File f : files) {
  8. delFile(f);
  9. }
  10. }
  11. return file.delete();
  12. }

发表评论

表情:
评论列表 (有 0 条评论,36人围观)

还没有评论,来说两句吧...

相关阅读