diff --git a/src/main/java/cn/hellohao/controller/AdminController.java b/src/main/java/cn/hellohao/controller/AdminController.java index fc1fd6d..d3c6342 100644 --- a/src/main/java/cn/hellohao/controller/AdminController.java +++ b/src/main/java/cn/hellohao/controller/AdminController.java @@ -504,8 +504,10 @@ public class AdminController { try{ myProgress = JSON.parseObject(iRedisService.getValue(uuid).toString(), MyProgress.class); }catch (Exception e){ } + msg.setCode("110666"); + msg.setInfo("正在执行"); if (null == myProgress) { - jsonObject.put("succ", myProgress.getDelSuccessCount()); + jsonObject.put("succ", 0); jsonObject.put("errorlist", new ArrayList()); jsonObject.put("oklist", new ArrayList()); jsonObject.put("delover", false); @@ -514,15 +516,12 @@ public class AdminController { jsonObject.put("errorlist", myProgress.getDelErrorImgListt()); jsonObject.put("oklist", myProgress.getDelSuccessImgList()); jsonObject.put("delover", myProgress.getDelOCT()); + if(myProgress.getDelOCT()==1){ + System.out.println("循环遍历的值:"+myProgress.getDelOCT()); + msg.setCode("100"); + } } msg.setData(jsonObject); - if (myProgress.getDelOCT()==1) { - System.out.println("循环遍历的值:" + myProgress.getDelOCT()); - msg.setCode("100"); - } else { - msg.setCode("110666"); - msg.setInfo("正在执行"); - } return msg; } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/cn/hellohao/controller/AdminRootController.java b/src/main/java/cn/hellohao/controller/AdminRootController.java index bc2a67f..7c9277e 100644 --- a/src/main/java/cn/hellohao/controller/AdminRootController.java +++ b/src/main/java/cn/hellohao/controller/AdminRootController.java @@ -194,7 +194,7 @@ public class AdminRootController { } else if (key.getStorageType() == 6) { ret = COSImageupload.Initialize(key); } else if (key.getStorageType() == 7) { - ret = FTPImageupload.Initialize(key); + ret = FtpServiceImpl.Initialize(key); } else if (key.getStorageType() == 8) { ret = UFileImageupload.Initialize(key); } diff --git a/src/main/java/cn/hellohao/controller/IndexController.java b/src/main/java/cn/hellohao/controller/IndexController.java index fbc21eb..2c79546 100644 --- a/src/main/java/cn/hellohao/controller/IndexController.java +++ b/src/main/java/cn/hellohao/controller/IndexController.java @@ -39,13 +39,12 @@ public class IndexController { @Autowired private UploadServicel uploadServicel; @Autowired private deleImages deleimages; @Autowired private IRedisService iRedisService; - @Autowired private AlbumServiceImpl albumService; @Autowired private AppClientService appClientService; @RequestMapping(value = "/") public String Welcome(Model model, HttpServletRequest httpServletRequest) { model.addAttribute("name", "服务端程序"); - model.addAttribute("version", "20221027"); + model.addAttribute("version", "20230101"); model.addAttribute("ip", GetIPS.getIpAddr(httpServletRequest)); model.addAttribute("links", "tbed.hellohao.cn"); return "welcome"; diff --git a/src/main/java/cn/hellohao/controller/UserController.java b/src/main/java/cn/hellohao/controller/UserController.java index 6856f0f..988d8fe 100644 --- a/src/main/java/cn/hellohao/controller/UserController.java +++ b/src/main/java/cn/hellohao/controller/UserController.java @@ -45,21 +45,23 @@ public class UserController { @PostMapping("/register") @ResponseBody - public Msg Register(HttpSession httpSession, @RequestParam(value = "data", defaultValue = "") String data) {//Validated + public Msg Register(HttpServletRequest httpServletRequest, @RequestParam(value = "data", defaultValue = "") String data) { Msg msg = new Msg(); JSONObject jsonObj = JSONObject.parseObject(data); String username = jsonObj.getString("username"); String email = jsonObj.getString("email"); String password = Base64Encryption.encryptBASE64(jsonObj.getString("password").getBytes()); String verifyCodeForRegister = jsonObj.getString("verifyCode"); - ShearCaptcha redis_verifyCodeForRegister = (ShearCaptcha) httpSession.getAttribute("_hellohao_verifyCodeForRegister");//iRedisService.getValue(userIP+"_verifyCodeForRegister"); + Object redis_verifyCodeForRegister = iRedisService.getValue("verifyCodeForRegister_"+httpServletRequest.getHeader("verifyCodeForRegister")); if(!SetText.checkEmail(email)){ + //邮箱格式不正确 msg.setCode("110403"); msg.setInfo("邮箱格式不正确"); return msg; } String regex = "^\\w+$"; if(username.length()>20 || !username.matches (regex)){ + //用户名格式不正确 msg.setCode("110403"); msg.setInfo("用户名不得超过20位字符"); return msg; @@ -73,7 +75,7 @@ public class UserController { msg.setInfo("验证码不能为空。"); return msg; } - if(redis_verifyCodeForRegister.verify(verifyCodeForRegister.toLowerCase())){ + if((redis_verifyCodeForRegister.toString().toLowerCase()).compareTo((verifyCodeForRegister.toLowerCase()))==0){ User user = new User(); UploadConfig updateConfig = uploadConfigService.getUpdateConfig(); EmailConfig emailConfig = emailConfigService.getemail(); @@ -106,10 +108,12 @@ public class UserController { user.setEmail(email); user.setUsername(username); user.setPassword(password); + user.setToken(UUID.randomUUID().toString().replace("-", "")); Config config = configService.getSourceype(); Integer type = 0; if(emailConfig.getUsing()==1){ user.setIsok(0); + //注册完发激活链接 Thread thread = new Thread() { public void run() { Integer a = NewSendEmail.sendEmail(emailConfig,user.getUsername(), uid, user.getEmail(),config); @@ -118,6 +122,7 @@ public class UserController { thread.start(); msg.setInfo("注册成功,请注意查收邮箱尽快激活账户"); }else{ + //直接注册 user.setIsok(1); msg.setInfo("注册成功,快去登陆吧"); } @@ -131,13 +136,25 @@ public class UserController { @PostMapping("/login")//new @ResponseBody - public Msg login(HttpServletRequest request,HttpSession httpSession,@RequestParam(value = "data", defaultValue = "") String data) { + public Msg login(HttpServletRequest httpServletRequest,@RequestParam(value = "data", defaultValue = "") String data) { Msg msg = new Msg(); JSONObject jsonObj = JSONObject.parseObject(data); String email = jsonObj.getString("email"); String password = Base64Encryption.encryptBASE64(jsonObj.getString("password").getBytes()); String verifyCode = jsonObj.getString("verifyCode"); - ShearCaptcha redis_VerifyCode = (ShearCaptcha)httpSession.getAttribute("_hellohao_verifyCode"); + if(null == email || null == password || null == verifyCode){ + msg.setCode("5000"); + msg.setInfo("登录信息不正确"); + return msg; + } + if(email.replace(" ","").equals("") || password.replace(" ","").equals("") + || verifyCode.replace(" ","").equals("")){ + msg.setCode("5000"); + msg.setInfo("登录信息不正确"); + return msg; + } + + Object redis_VerifyCode = iRedisService.getValue("verifyCode_"+httpServletRequest.getHeader("verifyCode")); if(null==redis_VerifyCode){ msg.setCode("4035"); msg.setInfo("验证码已失效,请重新弄获取。"); @@ -147,13 +164,13 @@ public class UserController { msg.setInfo("验证码不能为空。"); return msg; } - if(redis_VerifyCode.verify(verifyCode.toLowerCase())){ + if((redis_VerifyCode.toString().toLowerCase()).compareTo((verifyCode.toLowerCase()))==0){ Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken tokenOBJ = new UsernamePasswordToken(email,password); tokenOBJ.setRememberMe(true); try { subject.login(tokenOBJ); - SecurityUtils.getSubject().getSession().setTimeout(3600000);//一小时 + SecurityUtils.getSubject().getSession().setTimeout(3600000); JSONObject jsonObject = new JSONObject(); User user = (User) SecurityUtils.getSubject().getPrincipal(); if(user.getIsok()==0){ @@ -197,7 +214,7 @@ public class UserController { } }else{ msg.setCode("40034"); - msg.setInfo("验证码不正确");//失效也要处理。 + msg.setInfo("验证码不正确"); } return msg; } @@ -236,15 +253,15 @@ public class UserController { return msg; } - @PostMapping("/retrievePass") //new + @PostMapping("/retrievePass") @ResponseBody - public Msg retrievePass(HttpServletRequest request,HttpSession httpSession, @RequestParam(value = "data", defaultValue = "") String data) { + public Msg retrievePass(HttpServletRequest httpServletRequest, @RequestParam(value = "data", defaultValue = "") String data) { Msg msg = new Msg(); try { JSONObject jsonObj = JSONObject.parseObject(data); String email = jsonObj.getString("email"); String retrieveCode = jsonObj.getString("retrieveCode"); - ShearCaptcha redis_verifyCodeForEmailRetrieve =(ShearCaptcha) httpSession.getAttribute("_hellohao_verifyCodeForEmailRetrieve");// iRedisService.getValue(userIP+"_verifyCodeForEmailRetrieve"); + Object redis_verifyCodeForEmailRetrieve =iRedisService.getValue("verifyCodeForRetrieve_"+httpServletRequest.getHeader("verifyCodeForRetrieve")); EmailConfig emailConfig = emailConfigService.getemail(); if(null==redis_verifyCodeForEmailRetrieve){ msg.setCode("4035"); @@ -255,12 +272,11 @@ public class UserController { msg.setInfo("验证码不能为空。"); return msg; } - if(!redis_verifyCodeForEmailRetrieve.verify(retrieveCode.toLowerCase())){ + if((redis_verifyCodeForEmailRetrieve.toString().toLowerCase()).compareTo((retrieveCode.toLowerCase()))!=0){ msg.setCode("40034"); msg.setInfo("验证码不正确"); return msg; } - Integer ret = userService.countmail(email); if(ret>0){ if(emailConfig.getUsing()==1){ @@ -275,7 +291,7 @@ public class UserController { Config config = configService.getSourceype(); Thread thread = new Thread() { public void run() { - Integer a = NewSendEmail.sendEmailFindPass(emailConfig,user.getUsername(), user.getUid(), user.getEmail(),config);//SendEmail.sendEmailT(message, user.getUsername(), user.getUid(), user.getEmail(),emailConfig,config); + Integer a = NewSendEmail.sendEmailFindPass(emailConfig,user.getUsername(), user.getUid(), user.getEmail(),config); } }; thread.start(); @@ -296,7 +312,7 @@ public class UserController { return msg; } - @RequestMapping(value = "/retrieve", method = RequestMethod.GET) //new + @RequestMapping(value = "/retrieve", method = RequestMethod.GET) public String retrieve(Model model, String activation,String cip) { Integer ret = 0; try { diff --git a/src/main/java/cn/hellohao/quartz/job/FirstJob.java b/src/main/java/cn/hellohao/quartz/job/FirstJob.java index 4601205..f06e116 100644 --- a/src/main/java/cn/hellohao/quartz/job/FirstJob.java +++ b/src/main/java/cn/hellohao/quartz/job/FirstJob.java @@ -34,7 +34,7 @@ public class FirstJob { @Autowired private UFileImageupload uFileImageupload; @Autowired - private FTPImageupload ftpImageupload; + private FtpServiceImpl ftpService; @Autowired ImgTempService imgTempService; @Autowired @@ -75,7 +75,7 @@ public class FirstJob { }else if(keys.getStorageType()==6){ firstJob.cosImageupload.delCOS(keys.getId(),images); }else if(keys.getStorageType()==7){ - firstJob.ftpImageupload.delFTP(keys.getId(), images); + firstJob.ftpService.delFTP(keys.getId(), images); }else if(keys.getStorageType()==8){ firstJob.uFileImageupload.delUFile(keys.getId(), images); }else{ diff --git a/src/main/java/cn/hellohao/service/impl/ClientService.java b/src/main/java/cn/hellohao/service/impl/ClientService.java index 4bb4c15..8e7455f 100644 --- a/src/main/java/cn/hellohao/service/impl/ClientService.java +++ b/src/main/java/cn/hellohao/service/impl/ClientService.java @@ -35,13 +35,14 @@ public class ClientService { @Autowired private ImgMapper imgMapper; @Autowired private ImgreviewMapper imgreviewMapper; @Autowired private ImgTempService imgTempService; - @Autowired private KeysServiceImpl keysService; + @Autowired private GetSource getSource; public Msg uploadImg( HttpServletRequest request, MultipartFile multipartFile, String email, String pass,Integer setday) { Msg msg = new Msg(); try { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String imageFileName = "未命名图像"; Integer sourceKeyId = 0; FileInputStream fis = null; String md5key = null; @@ -53,6 +54,7 @@ public class ClientService { msg.setInfo("管理员关闭了API接口"); return msg; } + imageFileName = multipartFile.getOriginalFilename(); File file = SetFiles.changeFile_new(multipartFile); User u2 = new User(); if (!file.exists() || email == null || pass == null) { @@ -115,19 +117,6 @@ public class ClientService { } } } -// if (Integer.valueOf(sysConfigService.getstate().getCheckduplicate()) == 1) { -// Images imaOBJ = new Images(); -// imaOBJ.setMd5key(md5key); -// imaOBJ.setUserid(u.getId()); -// if (imgMapper.md5Count(imaOBJ) > 0) { -// List images = imgMapper.selectImgUrlByMD5(md5key); -// jsonObject.put("url", images.get(0).getImgurl()); -// jsonObject.put("name", file.getName()); -// jsonObject.put("size", images.get(0).getSizes()); -// msg.setData(jsonObject); -// return msg; -// } -// } Images imgObj = new Images(); String imgnameEd = null; Map, File> map = new HashMap<>(); @@ -145,6 +134,10 @@ public class ClientService { imgObj.setImgurl(key.getRequestAddress() + "/" + imgnameEd); } imgObj.setSizes(Long.toString(file.length())); + }else{ + msg.setInfo("未获取到指定图像:110503"); + msg.setCode("110503"); + return msg; } imgObj.setUpdatetime(df.format(new Date())); imgObj.setSource(key.getId()); @@ -162,6 +155,7 @@ public class ClientService { imgObj.setMd5key(md5key); imgObj.setImguid(imguid); imgObj.setFormat(fileMiME.getData().toString()); + imgObj.setIdname(imageFileName); Integer insertRet = imgMapper.insertImgData(imgObj); if (insertRet == 0) { Images imaOBJ = new Images(); @@ -191,9 +185,7 @@ public class ClientService { } } long stime = System.currentTimeMillis(); - Map m = null; - ReturnImage returnImage = - GetSource.storageSource(key.getStorageType(), map, updatePath, key.getId()); + ReturnImage returnImage = getSource.storageSource(key.getStorageType(), map, updatePath, key.getId()); if (returnImage.getCode().equals("200")) { long etime = System.currentTimeMillis(); Print.Normal("上传图片所用总时长:" + String.valueOf(etime - stime) + "ms"); diff --git a/src/main/java/cn/hellohao/service/impl/FTPImageupload.java b/src/main/java/cn/hellohao/service/impl/FTPImageupload.java deleted file mode 100644 index be3636c..0000000 --- a/src/main/java/cn/hellohao/service/impl/FTPImageupload.java +++ /dev/null @@ -1,132 +0,0 @@ -package cn.hellohao.service.impl; - -import cn.hellohao.pojo.Images; -import cn.hellohao.pojo.Keys; -import cn.hellohao.pojo.ReturnImage; -import cn.hellohao.utils.FTPUtils; -import cn.hellohao.utils.Print; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.net.ftp.FTPClient; -import org.apache.commons.net.ftp.FTPReply; -import org.springframework.stereotype.Service; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Map; - -@Service -public class FTPImageupload { - static Keys key; - - public ReturnImage ImageuploadFTP( - Map, File> fileMap, String username, Integer keyID) { - ReturnImage returnImage = new ReturnImage(); - String[] host = key.getEndpoint().split("\\:"); - String h = host[0]; - Integer p = Integer.parseInt(host[1]); - FTPUtils ftps = new FTPUtils(h, p, key.getAccessKey(), key.getAccessSecret()); - boolean flag = ftps.open(); - File file = null; - ftps.mkDir(File.separator + username); - try { - for (Map.Entry, File> entry : fileMap.entrySet()) { - String prefix = entry.getKey().get("prefix"); - String ShortUIDName = entry.getKey().get("name"); - file = entry.getValue(); - String userkey = username + "/" + ShortUIDName + "." + prefix; - if (flag) { - boolean isUpload = ftps.upload(file, "/" + userkey, ""); - if (isUpload) { - - } else { - returnImage.setCode("400"); - } - - } else { - returnImage.setCode("400"); - } - Print.Normal("要上传的文件路径:/" + userkey); - } - returnImage.setCode("200"); - } catch (Exception e) { - e.printStackTrace(); - returnImage.setCode("500"); - } - return returnImage; - } - - public static Integer Initialize(Keys k) { - int ret = -1; - if (StringUtils.isBlank(k.getAccessKey()) - || StringUtils.isBlank(k.getAccessSecret()) - || StringUtils.isBlank(k.getEndpoint()) - || StringUtils.isBlank(k.getRequestAddress())) { - return -1; - } - FTPClient ftp = new FTPClient(); - ftp.setConnectTimeout(0); - int flag = k.getEndpoint().indexOf(":"); - if (flag > 0) { - String[] host = k.getEndpoint().split("\\:"); - String h = host[0]; - Integer p = Integer.parseInt(host[1]); - try { - if (!ftp.isConnected()) { - ftp.connect(h, p); - } - ftp.login(k.getAccessKey(), k.getAccessSecret()); - int reply = ftp.getReplyCode(); - if (!FTPReply.isPositiveCompletion(reply)) { - System.out.println("FTP Object Is null"); - ftp.disconnect(); - return -1; - } - ret = 1; - key = k; - } catch (IOException e) { - System.out.println("FTP Object Is null"); - return -1; - } - } - return ret; - } - - public static void copyFile(String p1, String p2) { - String a = p1; - try { - File afile = new File(a); - File bfile = new File(p2); // 定义一个复制后的文件路径 - bfile.createNewFile(); - FileInputStream c = new FileInputStream(afile); - FileOutputStream d = new FileOutputStream(bfile); - byte[] date = new byte[512]; - int i = 0; - while ((i = c.read(date)) > 0) { - d.write(date); - } - c.close(); - d.close(); - System.out.println("文件复制成功"); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public Boolean delFTP(Integer keyID, Images images) { - boolean b = true; - try { - String[] host = key.getEndpoint().split("\\:"); - String h = host[0]; - Integer p = Integer.parseInt(host[1]); - FTPUtils ftps = new FTPUtils(h, p, key.getAccessKey(), key.getAccessSecret()); - ftps.open(); - b = ftps.deleteFile(images.getImgname()); - } catch (Exception e) { - e.printStackTrace(); - b = false; - } - return b; - } -} diff --git a/src/main/java/cn/hellohao/service/impl/FtpServiceImpl.java b/src/main/java/cn/hellohao/service/impl/FtpServiceImpl.java new file mode 100644 index 0000000..740eeb9 --- /dev/null +++ b/src/main/java/cn/hellohao/service/impl/FtpServiceImpl.java @@ -0,0 +1,107 @@ +package cn.hellohao.service.impl; + +import cn.hellohao.pojo.Images; +import cn.hellohao.pojo.Keys; +import cn.hellohao.pojo.ReturnImage; +import cn.hutool.extra.ftp.Ftp; +import cn.hutool.extra.ftp.FtpMode; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.net.ftp.FTP; +import org.springframework.stereotype.Service; + +import java.io.File; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +@Service +public class FtpServiceImpl { + private Keys key; + + public static int Initialize(Keys k) { + int ret = -1; + try{ + if (StringUtils.isBlank(k.getAccessKey()) + || StringUtils.isBlank(k.getAccessSecret()) + || StringUtils.isBlank(k.getEndpoint()) + || StringUtils.isBlank(k.getRequestAddress())){ + return -1; + } + Charset charset = StandardCharsets.UTF_8;//Charset.forName("UTF-8"); + String[] hostArr = k.getEndpoint().split("\\:"); + String host = hostArr[0]; + Integer port = Integer.parseInt(hostArr[1]); + Ftp ftp = new Ftp(host, port, k.getAccessKey(), k.getAccessSecret(), charset); + ftp.getClient().type(FTP.BINARY_FILE_TYPE); + ftp.setMode(FtpMode.Passive); + return 1; + } catch (Exception e) { + e.printStackTrace(); + return -1; + } + } + + public ReturnImage FtpUploadFile( + Map, File> fileMap, String username, Integer keyID) { + ReturnImage returnImage = new ReturnImage(); + Ftp ftp = null; + try { + if (null == key) { + System.out.println("FTP = 存储源对象为空"); + returnImage.setCode("500"); + return returnImage; + } + Charset charset = StandardCharsets.UTF_8;//Charset.forName("UTF-8"); + String[] hostArr = key.getEndpoint().split("\\:"); + String host = hostArr[0]; + Integer port = Integer.parseInt(hostArr[1]); + ftp = new Ftp(host, port, key.getAccessKey(), key.getAccessSecret(), charset); + ftp.getClient().type(FTP.BINARY_FILE_TYPE); + ftp.setMode(FtpMode.Passive); + + } catch (Exception e) { + e.printStackTrace(); + System.out.println("FTP = 存储源对象为空"); + returnImage.setCode("500"); + return returnImage; + } + File file = null; + try { + for (Map.Entry, File> entry : fileMap.entrySet()) { + String prefix = entry.getKey().get("prefix"); + String ShortUIDName = entry.getKey().get("name"); + file = entry.getValue(); + boolean isUpload = ftp.upload( + "/" + username, + ShortUIDName + "." + prefix, + file); + if (!isUpload) { + returnImage.setCode("400"); + } + } + returnImage.setCode("200"); + } catch (Exception e) { + e.printStackTrace(); + returnImage.setCode("500"); + } + return returnImage; + } + + public Boolean delFTP(Integer keyID, Images images) { + boolean b = true; + Ftp ftp = null; + try { + Charset charset = StandardCharsets.UTF_8;//Charset.forName("UTF-8"); + String[] hostArr = key.getEndpoint().split("\\:"); + String host = hostArr[0]; + Integer port = Integer.parseInt(hostArr[1]); + ftp = new Ftp(host, port, key.getAccessKey(), key.getAccessSecret(), charset); + b = ftp.delFile(images.getImgname()); + } catch (Exception e) { + e.printStackTrace(); + b = false; + } + return b; + } + +} diff --git a/src/main/java/cn/hellohao/service/impl/InitializationStorage.java b/src/main/java/cn/hellohao/service/impl/InitializationStorage.java index 6076489..a040b07 100644 --- a/src/main/java/cn/hellohao/service/impl/InitializationStorage.java +++ b/src/main/java/cn/hellohao/service/impl/InitializationStorage.java @@ -53,7 +53,7 @@ public class InitializationStorage implements CommandLineRunner { }else if(key.getStorageType()==6){ ret = COSImageupload.Initialize(key); }else if(key.getStorageType()==7){ - ret = FTPImageupload.Initialize(key); + ret = FtpServiceImpl.Initialize(key); }else if(key.getStorageType()==8){ ret = UFileImageupload.Initialize(key); } diff --git a/src/main/java/cn/hellohao/service/impl/KeysServiceImpl.java b/src/main/java/cn/hellohao/service/impl/KeysServiceImpl.java index c01cd9b..95c1f6c 100644 --- a/src/main/java/cn/hellohao/service/impl/KeysServiceImpl.java +++ b/src/main/java/cn/hellohao/service/impl/KeysServiceImpl.java @@ -28,7 +28,7 @@ public class KeysServiceImpl implements KeysService { @Autowired private COSImageupload cosImageupload; @Autowired - private FTPImageupload ftpImageupload; + private FtpServiceImpl ftpService; @Autowired private UFileImageupload uFileImageupload; @@ -65,7 +65,7 @@ public class KeysServiceImpl implements KeysService { }else if(key.getStorageType()==6){ ret = cosImageupload.Initialize(key); }else if(key.getStorageType()==7){ - ret = ftpImageupload.Initialize(key); + ret = ftpService.Initialize(key); }else if(key.getStorageType()==8){ ret = uFileImageupload.Initialize(key); }else{ diff --git a/src/main/java/cn/hellohao/service/impl/UploadServicel.java b/src/main/java/cn/hellohao/service/impl/UploadServicel.java index aea5e45..519ca58 100644 --- a/src/main/java/cn/hellohao/service/impl/UploadServicel.java +++ b/src/main/java/cn/hellohao/service/impl/UploadServicel.java @@ -34,7 +34,7 @@ public class UploadServicel { @Autowired private UserMapper userMapper; @Autowired private ImgreviewMapper imgreviewMapper; @Autowired private ImgTempService imgTempService; - @Autowired private KeysServiceImpl keysService; + @Autowired private GetSource getSource; public Msg uploadForLoc( HttpServletRequest request, @@ -44,6 +44,7 @@ public class UploadServicel { Msg msg = new Msg(); try { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String imageFileName = "未命名图像"; JSONObject jsonObject = new JSONObject(); UploadConfig uploadConfig = uploadConfigMapper.getUpdateConfig(); String userip = GetIPS.getIpAddr(request); @@ -57,8 +58,10 @@ public class UploadServicel { FileInputStream fis = null; File file = null; if (imgUrl == null) { + imageFileName = multipartFile.getOriginalFilename(); file = SetFiles.changeFile_new(multipartFile); } else { + imageFileName = "URL转存图像"; Msg imgData = uploadForURL(request, imgUrl); if (imgData.getCode().equals("200")) { file = new File((String) imgData.getData()); @@ -102,19 +105,6 @@ public class UploadServicel { if (md5key == null || md5key.equals("")) { md5key = UUID.randomUUID().toString().replace("-", ""); } - // if(Integer.valueOf(sysConfigService.getstate().getCheckduplicate())==1){ - // Images imaOBJ = new Images(); - // imaOBJ.setMd5key(md5key); - // imaOBJ.setUserid(u==null?0:u.getId()); - // if(imgMapper.md5Count(imaOBJ)>0){ - // List images = imgMapper.selectImgUrlByMD5(md5key); - // jsonObject.put("url", images.get(0).getImgurl()); - // jsonObject.put("name",file.getName()); - // jsonObject.put("imguid",images.get(0).getImguid()); - // msg.setData(jsonObject); - // return msg; - // } - // } String prefix = file.getName().substring(file.getName().lastIndexOf(".") + 1); // 判断黑名单 if (uploadConfig.getBlacklist() != null) { @@ -146,6 +136,10 @@ public class UploadServicel { imgObj.setImgurl(key.getRequestAddress() + "/" + imgnameEd); } imgObj.setSizes(Long.toString(file.length())); + }else{ + msg.setInfo("未获取到指定图像:110503"); + msg.setCode("110503"); + return msg; } imgObj.setUpdatetime(df.format(new Date())); imgObj.setSource(key.getId()); @@ -163,6 +157,7 @@ public class UploadServicel { imgObj.setMd5key(md5key); imgObj.setImguid(imguid); imgObj.setFormat(fileMiME.getData().toString()); + imgObj.setIdname(imageFileName); Integer insertRet = imgMapper.insertImgData(imgObj); if (insertRet == 0) { Images imaOBJ = new Images(); @@ -192,8 +187,7 @@ public class UploadServicel { } } long stime = System.currentTimeMillis(); - ReturnImage returnImage = - GetSource.storageSource(key.getStorageType(), map, updatePath, key.getId()); + ReturnImage returnImage = getSource.storageSource(key.getStorageType(), map, updatePath, key.getId()); if (returnImage.getCode().equals("200")) { long etime = System.currentTimeMillis(); Print.Normal("上传图片所用总时长:" + String.valueOf(etime - stime) + "ms"); diff --git a/src/main/java/cn/hellohao/service/impl/deleImages.java b/src/main/java/cn/hellohao/service/impl/deleImages.java index 0dfc586..45cb863 100644 --- a/src/main/java/cn/hellohao/service/impl/deleImages.java +++ b/src/main/java/cn/hellohao/service/impl/deleImages.java @@ -25,7 +25,7 @@ public class deleImages { @Autowired private KODOImageupload kodoImageupload; @Autowired private USSImageupload ussImageupload; @Autowired private UFileImageupload uFileImageupload; - @Autowired private FTPImageupload ftpImageupload; + @Autowired private FtpServiceImpl ftpService; @Autowired private ImgAndAlbumService imgAndAlbumService; @Autowired private ImgTempService imgTempService; @Autowired private ImgService imgService; @@ -58,26 +58,26 @@ public class deleImages { } else if (key.getStorageType() == 6) { isDele = cosImageupload.delCOS(key.getId(), image); } else if (key.getStorageType() == 7) { - isDele = ftpImageupload.delFTP(key.getId(), image); + isDele = ftpService.delFTP(key.getId(), image); } else if (key.getStorageType() == 8) { isDele = uFileImageupload.delUFile(key.getId(), image); } else { System.err.println("未获取到对象存储参数,删除失败。"); } - if (isDele) { - try { - imgAndAlbumService.deleteImgAndAlbum(image.getImgurl()); - imgTempService.delImgAndExp(image.getImguid()); - imgService.deleimg(image.getId()); - ids.add(image.getId()); - successCount++; - System.out.println("删除成功加一个" + image.getId()); - } catch (Exception e) { - e.printStackTrace(); - System.err.println(image.getImgname() + ":图片数据库记录时发生错误"); - errorIds.add(image.getImgurl()); - } +// if (isDele) { + try { + imgAndAlbumService.deleteImgAndAlbum(image.getImgurl()); + imgTempService.delImgAndExp(image.getImguid()); + imgService.deleimg(image.getId()); + ids.add(image.getId()); + successCount++; + System.out.println("删除成功加一个" + image.getId()); + } catch (Exception e) { + e.printStackTrace(); + System.err.println(image.getImgname() + ":图片数据库记录时发生错误"); + errorIds.add(image.getImgurl()); } +// } if(uuid!=null){ myProgress.setDelSuccessCount(successCount); myProgress.setDelSuccessImgList(ids); @@ -89,11 +89,21 @@ public class deleImages { } iRedisService.setTimeValue(uuid, JSONObject.toJSONString(myProgress), 24L); } - // if (null != httpSession) { - // httpSession.setAttribute("myProgressForDel", myProgress); - // } } catch (Exception e) { System.err.println("删除的时候发生了一些异常"); + ids.add(imgIds[i]); + successCount++; + if(uuid!=null){ + myProgress.setDelSuccessCount(successCount); + myProgress.setDelSuccessImgList(ids); + myProgress.setDelErrorImgListt(errorIds); + if (imgIds.length == (i + 1)) { + myProgress.setDelOCT(1); + } else { + myProgress.setDelOCT(0); + } + iRedisService.setTimeValue(uuid, JSONObject.toJSONString(myProgress), 24L); + } e.printStackTrace(); } } diff --git a/src/main/java/cn/hellohao/utils/FTPUtils.java b/src/main/java/cn/hellohao/utils/FTPUtils.java deleted file mode 100644 index 3db4215..0000000 --- a/src/main/java/cn/hellohao/utils/FTPUtils.java +++ /dev/null @@ -1,324 +0,0 @@ -package cn.hellohao.utils; - -import org.apache.commons.net.ftp.FTP; -import org.apache.commons.net.ftp.FTPClient; -import org.apache.commons.net.ftp.FTPFile; -import org.apache.commons.net.ftp.FTPReply; -import org.apache.log4j.LogManager; -import org.apache.log4j.Logger; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; - -/** - *

Title:

- *

Description:

- * - * @author Hellohao - * @date 2019年11月10日 - */ -public class FTPUtils { - private final Logger LOGGER = LogManager.getLogger(getClass()); - private FTPClient ftpClient = null; - private String server; - private int port; - private String userName; - private String userPassword; - public FTPUtils(String server, int port, String userName, String userPassword) { - this.server = server; - this.port = port; - this.userName = userName; - this.userPassword = userPassword; - } - - public boolean open() { - // 判断是否已连接 - if (ftpClient != null && ftpClient.isConnected()) { - return true; - } - try { - ftpClient = new FTPClient(); - // 连接FTP服务器 - ftpClient.connect(this.server, this.port); - ftpClient.login(this.userName, this.userPassword); - int reply = ftpClient.getReplyCode(); - if (!FTPReply.isPositiveCompletion(reply)) { - Print.warning("FTP服务器拒绝连接."); - this.close(); - System.exit(1); - } - ftpClient.setFileType(FTP.BINARY_FILE_TYPE); - ftpClient.enterLocalPassiveMode(); - return true; - } catch (Exception e) { - this.close(); - e.printStackTrace(); - return false; - } - - } - - /** - *

Title: 切换到父目录

- *

Description:

- * - * @author Hellohao - * @date 2018年10月11日 - * - * @return 切换结果 true:成功, false:失败 - */ - private boolean changeToParentDir() { - try { - return ftpClient.changeToParentDirectory(); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - } - - /** - * - * @param dir 目的目录 - * @return 切换结果 true:成功,false:失败 - */ - private boolean cd(String dir) { - try { - return ftpClient.changeWorkingDirectory(dir); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - } - - /** - * - * @param filePath 指定的目录 - * @return 文件列表,或者null - */ - private FTPFile[] getFileList(String filePath) { - try { - return ftpClient.listFiles(filePath); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - /** - * - * @param ftpPath 目的目录 - * @return 切换结果 - */ - public boolean changeDir(String ftpPath) { - if (!ftpClient.isConnected()) { - return false; - } - try { - char[] chars = ftpPath.toCharArray(); - StringBuffer sbStr = new StringBuffer(256); - for (int i = 0; i < chars.length; i++) { - if ('\\' == chars[i]) { - sbStr.append('/'); - } else { - sbStr.append(chars[i]); - } - } - ftpPath = sbStr.toString(); - if (ftpPath.indexOf('/') == -1) { - // 只有一层目录 - ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "UTF-8")); - } else { - // 多层目录循环创建 - String[] paths = ftpPath.split("/"); - for (int i = 0; i < paths.length; i++) { - ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "UTF-8")); - } - } - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * @param ftpPath 需要创建的目录 - * @return - */ - public boolean mkDir(String ftpPath) { - if (!ftpClient.isConnected()) { - return false; - } - try { - // 将路径中的斜杠统一 - char[] chars = ftpPath.toCharArray(); - StringBuffer sbStr = new StringBuffer(256); - for (int i = 0; i < chars.length; i++) { - if ('\\' == chars[i]) { - sbStr.append('/'); - } else { - sbStr.append(chars[i]); - } - } - ftpPath = sbStr.toString(); - if (ftpPath.indexOf('/') == -1) { - // 只有一层目录 - ftpClient.makeDirectory(new String(ftpPath.getBytes(), "UTF-8")); - ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "UTF-8")); - } else { - // 多层目录循环创建 - String[] paths = ftpPath.split("/"); - for (int i = 0; i < paths.length; i++) { - ftpClient.makeDirectory(new String(paths[i].getBytes(), "UTF-8")); - ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "UTF-8")); - } - } - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - /** - * - * @param //localDirectoryAndFileName 本地文件目录和文件名 - * @param ftpFileName 上传到服务器的文件名() - * @param ftpDirectory FTP目录如:/path1/pathb2/,如果目录不存在会自动创建目录(目录可以省略) - * @return - */ - public boolean upload(File srcFile, String ftpFileName, String ftpDirectory) { - if (!ftpClient.isConnected()) { - return false; - } - boolean flag = false; - if (ftpClient != null) { - FileInputStream fis = null; - try { - fis = new FileInputStream(srcFile); - // 创建目录 - this.mkDir(ftpDirectory); - ftpClient.setBufferSize(100000); - ftpClient.setControlEncoding("UTF-8"); - // 设置文件类型(二进制) - ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); - - if (ftpFileName == null || ftpFileName == "") { - ftpFileName = srcFile.getName(); - } - // 上传 - flag = ftpClient.storeFile(new String(ftpFileName.getBytes(), "UTF-8"), fis); - } catch (Exception e) { - this.close(); - e.printStackTrace(); - return false; - } finally { - try { - fis.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - return flag; - } - - /** - * @param ftpDirectoryAndFileName ftp服务器文件路径,以/dir形式开始 - * @param localDirectoryAndFileName 保存到本地的目录 - * @return - */ - public boolean get(String ftpDirectoryAndFileName, String localDirectoryAndFileName) { - if (!ftpClient.isConnected()) { - return false; - } - ftpClient.enterLocalPassiveMode(); - try { - // 将路径中的斜杠统一 - char[] chars = ftpDirectoryAndFileName.toCharArray(); - StringBuffer sbStr = new StringBuffer(256); - for (int i = 0; i < chars.length; i++) { - if ('\\' == chars[i]) { - sbStr.append('/'); - } else { - sbStr.append(chars[i]); - } - } - ftpDirectoryAndFileName = sbStr.toString(); - String filePath = ftpDirectoryAndFileName.substring(0, ftpDirectoryAndFileName.lastIndexOf("/")); - String fileName = ftpDirectoryAndFileName.substring(ftpDirectoryAndFileName.lastIndexOf("/") + 1); - this.changeDir(filePath); - ftpClient.retrieveFile(new String(fileName.getBytes(), "UTF-8"), new FileOutputStream(localDirectoryAndFileName)); // download - return true; - } catch (IOException e) { - e.printStackTrace(); - return false; - } - } - - /** - * - * @param pathName - * @return - */ - public String[] getFileNameList(String pathName) { - try { - return ftpClient.listNames(pathName); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - /** - *

Title: 删除FTP上的文件

- *

Description:

- * @param ftpDirAndFileName 路径开头不能加/,比如应该是test/filename1 - * @return - */ - public boolean deleteFile(String ftpDirAndFileName) { - if (!ftpClient.isConnected()) { - return false; - } - try { - return ftpClient.deleteFile(ftpDirAndFileName); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - } - - /** - * @param ftpDirectory - * @return - */ - public boolean deleteDirectory(String ftpDirectory) { - if (!ftpClient.isConnected()) { - return false; - } - try { - return ftpClient.removeDirectory(ftpDirectory); - } catch (IOException e) { - e.printStackTrace(); - return false; - } - } - - /** - *

Title: 关闭链接

- *

Description:

- */ - public void close() { - try { - if (ftpClient != null && ftpClient.isConnected()) { - ftpClient.disconnect(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - -} diff --git a/src/main/java/cn/hellohao/utils/FirstRun.java b/src/main/java/cn/hellohao/utils/FirstRun.java index d66afe0..249fe4a 100644 --- a/src/main/java/cn/hellohao/utils/FirstRun.java +++ b/src/main/java/cn/hellohao/utils/FirstRun.java @@ -96,12 +96,10 @@ public class FirstRun implements InitializingBean { // RunSqlScript.RunInsert(sql11); // Print.Normal("Add imgdata.idname"); // } - - RunSqlScript.RunInsert("alter table `config` modify column `explain` text,modify column `links` text,modify column `notice` text,modify column `baidu` text"); - - //RunSqlScript.RunInsert("alter table imgdata drop index index_md5key_url"); - RunSqlScript.RunInsert(inddx_md5key); - RunSqlScript.RunInsert("UPDATE `keys` SET `Endpoint` = '0' WHERE `id` = 8"); + RunSqlScript.RunInsert("alter table tbed.`config` modify column `explain` text,modify column `links` text,modify column `notice` text,modify column `baidu` text"); +// RunSqlScript.RunInsert(inddx_md5key); + RunSqlScript.RunInsert("UPDATE tbed.`keys` SET `Endpoint` = '0' WHERE `id` = 8"); + RunSqlScript.RunInsert("ALTER TABLE tbed.`user` MODIFY id int auto_increment;"); Print.Normal("Stage success"); clears(); diff --git a/src/main/java/cn/hellohao/utils/GetSource.java b/src/main/java/cn/hellohao/utils/GetSource.java index 23c03df..fbcb238 100644 --- a/src/main/java/cn/hellohao/utils/GetSource.java +++ b/src/main/java/cn/hellohao/utils/GetSource.java @@ -3,6 +3,8 @@ package cn.hellohao.utils; import cn.hellohao.exception.StorageSourceInitException; import cn.hellohao.pojo.ReturnImage; import cn.hellohao.service.impl.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.File; @@ -13,15 +15,25 @@ import java.util.Map; * @version 1.0 * @date 2019/11/7 17:12 */ +@Service public class GetSource { - public static ReturnImage storageSource(Integer type, Map, File> fileMap, String userpath,Integer keyID){ - NOSImageupload nosImageupload = SpringContextHolder.getBean(NOSImageupload.class); - OSSImageupload ossImageupload = SpringContextHolder.getBean(OSSImageupload.class); - USSImageupload ussImageupload = SpringContextHolder.getBean(USSImageupload.class); - KODOImageupload kodoImageupload = SpringContextHolder.getBean(KODOImageupload.class); - COSImageupload cosImageupload = SpringContextHolder.getBean(COSImageupload.class); - FTPImageupload ftpImageupload = SpringContextHolder.getBean(FTPImageupload.class); - UFileImageupload uFileImageupload = SpringContextHolder.getBean(UFileImageupload.class); + + @Autowired + NOSImageupload nosImageupload; + @Autowired + OSSImageupload ossImageupload; + @Autowired + USSImageupload ussImageupload; + @Autowired + KODOImageupload kodoImageupload; + @Autowired + COSImageupload cosImageupload; + @Autowired + FtpServiceImpl ftpService; + @Autowired + UFileImageupload uFileImageupload; + + public ReturnImage storageSource(Integer type, Map, File> fileMap, String userpath,Integer keyID){ ReturnImage returnImage = null; try { if(type==1){ @@ -37,7 +49,7 @@ public class GetSource { }else if(type==6){ returnImage = cosImageupload.ImageuploadCOS(fileMap, userpath,keyID);; }else if(type==7){ - returnImage = ftpImageupload.ImageuploadFTP(fileMap, userpath,keyID); + returnImage = ftpService.FtpUploadFile(fileMap, userpath,keyID); }else if(type==8){ returnImage = uFileImageupload.ImageuploadUFile(fileMap, userpath,keyID); }