2019-07-31更新 增加FTP上传

This commit is contained in:
Hellohao
2019-07-31 22:12:24 +08:00
parent 23f123892f
commit 14825399e6
16 changed files with 810 additions and 78 deletions
+6
View File
@@ -82,6 +82,12 @@
<artifactId>cos_api</artifactId>
<version>5.5.7</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
<!--hutool-->
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
@@ -229,6 +229,8 @@ public class AdminController {
LocUpdateImg.deleteLOCImg(images.getImgname());
}else if (key.getStorageType() == 6) {
de.delectCOS(key, images.getImgname());
}else if (key.getStorageType() == 7) {
de.delectFTP(key, images.getImgname());
}else {
System.err.println("未获取到对象存储参数,删除失败。");
}
@@ -280,6 +282,8 @@ public class AdminController {
LocUpdateImg.deleteLOCImg(images.getImgname());
}else if (key.getStorageType() == 6) {
de.delectCOS(key, images.getImgname());
}else if (key.getStorageType() == 7) {
de.delectFTP(key, images.getImgname());
}else {
System.err.println("未获取到对象存储参数,删除失败。");
}
@@ -42,6 +42,8 @@ public class UpdateImgController {
private KODOImageupload kodoImageupload;
@Autowired
private COSImageupload cosImageupload;
@Autowired
private FTPImageupload ftpImageupload;
@RequestMapping({"/", "/index"})
public String indexImg(Model model, HttpSession httpSession) {
@@ -73,6 +75,8 @@ public class UpdateImgController {
KODOImageupload.Initialize(key);
}else if(key.getStorageType()==6){
COSImageupload.Initialize(key);
}else if(key.getStorageType()==7){
FTPImageupload.Initialize(key);
}
else{
Print.Normal("为获取到存储参数,或者使用存储源是本地的。");
@@ -121,6 +125,7 @@ public class UpdateImgController {
@ResponseBody
public String upimg( HttpSession session
, @RequestParam(value = "file", required = false) MultipartFile[] file) throws Exception {
Config config = configService.getSourceype();//查询当前系统使用的存储源类型。
UploadConfig uploadConfig = uploadConfigService.getUpdateConfig();
User u = (User) session.getAttribute("user");
@@ -152,7 +157,7 @@ public class UpdateImgController {
String lastname = fileName.substring(fileName.lastIndexOf(".") + 1);//获取文件后缀
if (!multipartFile.isEmpty()) { //判断文件是否为空
map.put(lastname, multipartFile);
//multipartFile.getOriginalFilename(); //文件名
System.out.println("===name==="+multipartFile.getOriginalFilename()); //文件名
//multipartFile.getSize(); //文件大小
}
}
@@ -169,6 +174,8 @@ public class UpdateImgController {
m = LocUpdateImg.ImageuploadLOC(map, userpath,null);
}else if(key.getStorageType()==6){
m = cosImageupload.ImageuploadCOS(map, userpath,null);
}else if(key.getStorageType()==7){
m = ftpImageupload.ImageuploadFTP(map, userpath,null);
}
else{
System.err.println("未获取到对象存储参数,上传失败。");
@@ -295,6 +302,8 @@ public class UpdateImgController {
m = LocUpdateImg.ImageuploadLOC(null,userpath,map);
}else if(key.getStorageType()==6){
m = cosImageupload.ImageuploadCOS(null,userpath,map);
}else if(key.getStorageType()==7){
m = ftpImageupload.ImageuploadFTP(null,userpath,map);
}
else{
System.err.println("未获取到对象存储参数,上传失败。");
@@ -314,8 +323,8 @@ public class UpdateImgController {
}
}else{
jsonArray.add(entry.getKey().getImgurl());
img.setImgurl(entry.getKey().getImgurl());
}
//img.setImgurl(entry.getKey());//图片链接
img.setUpdatetime(times);
img.setSource(key.getStorageType());
if (u == null) {
@@ -377,6 +386,8 @@ public class UpdateImgController {
m =LocUpdateImg.ImageuploadLOC(null,userpath, map);
}else if(key.getStorageType()==6){
m =cosImageupload.ImageuploadCOS(null,userpath, map);
}else if(key.getStorageType()==7){
m = ftpImageupload.ImageuploadFTP(null,userpath,map);
}
else{
System.err.println("未获取到对象存储参数,上传失败。");
@@ -0,0 +1,193 @@
package cn.hellohao.service.impl;
import cn.hellohao.pojo.Keys;
import cn.hellohao.pojo.ReturnImage;
import cn.hellohao.utils.FTPUtils;
import cn.hellohao.utils.ImgUrlUtil;
import cn.hellohao.utils.Print;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
@Service
public class FTPImageupload {
static FTPClient ftpClient1 ;
static Keys key;
public Map<ReturnImage, Integer> ImageuploadFTP(Map<String, MultipartFile> fileMap, String username,Map<String, String> fileMap2) throws Exception {
String[] host = key.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
//创建FTP客户端,所有的操作都基于FTPClinet
FTPUtils ftps = new FTPUtils(h, p, key.getAccessKey(), key.getAccessSecret());
boolean flag = ftps.open();
if(fileMap2==null){
File file = null;
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
ftps.mkDir(File.separator+username);
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
System.out.println("文件地址:"+file.toString());
String userkey =username + File.separator+ uuid+times + "." + entry.getKey();
//fuzhi(file.toString(),File.separator+"tmp"+File.separator+uuid+times + "." + entry.getKey());
if (flag) {
// 上传
//ftps.upload(File.separator+"tmp"+File.separator+uuid+times + "." + entry.getKey(), File.separator+userkey, "");
ftps.upload(file, File.separator+userkey, "");
//boolean isSet = ftp.sendSiteCommand("chmod 744 " + File.separator+userkey);//设置权限
ReturnImage returnImage = new ReturnImage();
returnImage.setImgname(entry.getValue().getOriginalFilename());
returnImage.setImgurl(key.getRequestAddress() + File.separator+ userkey);
ImgUrl.put(returnImage, (int) (entry.getValue().getSize()));
ftps.close();
}
Print.Normal("要上传的文件路径:"+File.separator+userkey);
}
return ImgUrl;
}else{
Map<ReturnImage, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, String> entry : fileMap2.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
String imgurl = entry.getValue();
File file = new File(imgurl);
String userkey =username + File.separator+ uuid+times + "." + entry.getKey();
ftps.mkDir(File.separator+username);
if (flag) {
ftps.upload(file, File.separator+userkey, "");
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + File.separator+ userkey);
Print.Normal("Url上传成功返回地址");
ImgUrl.put(returnImage, ImgUrlUtil.getFileSize2(new File(imgurl)));
ftps.close();
}
boolean bb= new File(imgurl).getAbsoluteFile().delete();
Print.Normal("删除情况"+bb);
}
return ImgUrl;
}
}
// 转换文件方法
private File changeFile(MultipartFile multipartFile) throws Exception {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
// todo 修改临时文件文件名
File file = File.createTempFile(fileName, prefix);
// MultipartFile to File
multipartFile.transferTo(file);
return file;
}
//初始化FTP对象存储
public static void Initialize(Keys k) {
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null && k.getRequestAddress()!=null ) {
FTPClient ftp = new FTPClient();
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());
} catch (IOException e) {
e.printStackTrace();
}
//获取服务器返回的状态码
int reply = ftp.getReplyCode();
System.out.println(reply);
/*
* 判断是否连接成功
* 所有以2开头的代码是正完成响应。
* FTP服务器将在最终发送一个肯定的完成响应成功完成命令。
*/
if (!FTPReply.isPositiveCompletion(reply)) {
try {
ftp.disconnect();
}catch (IOException e){
System.out.println(e);
}
Print.warning("连接失败");
return;
}
Print.Normal("链接成功");
//boolean isUpload = ftp.storeFile("/ftp/upload.jpg", fis);
ftpClient1 = ftp;
key = k;
}
}
/**
* 客户端接口
* */
public Map<String, Integer> clientuploadCOS(Map<String, MultipartFile> fileMap, String username) throws Exception {
String[] host = key.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
//创建FTP客户端,所有的操作都基于FTPClinet
FTPUtils ftps = new FTPUtils(h, p, key.getAccessKey(), key.getAccessSecret());
boolean flag = ftps.open();
File file = null;
Map<String, Integer> ImgUrl = new HashMap<>();
for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(0,5);//生成一个没有-的uuid,然后取前5位
java.text.DateFormat format1 = new java.text.SimpleDateFormat("MMddhhmmss");
String times = format1.format(new Date());
file = changeFile(entry.getValue());
String userkey =username + File.separator+ uuid+times + "." + entry.getKey();
ftps.mkDir(File.separator+username);
if (flag) {
ftps.upload(file, File.separator+userkey, "");
ReturnImage returnImage = new ReturnImage();
returnImage.setImgurl(key.getRequestAddress() + File.separator+ userkey);
ImgUrl.put(key.getRequestAddress() + File.separator+userkey + username + File.separator+userkey + uuid+times + "." + entry.getKey(), (int) (entry.getValue().getSize()));
ftps.close();
}
}
return ImgUrl;
}
public static void fuzhi(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);//定义FileInputStream对象
FileOutputStream d=new FileOutputStream(bfile);//定义FileOutputStream对象
byte[] date=new byte[512];//定义一个byte数组
int i=0;
while((i=c.read(date))>0){//判断有没有读取到文件末尾
d.write(date);//写数据
}
c.close();//关闭流
d.close();//关闭流
System.out.println("文件复制成功");}
catch(IOException e){
e.printStackTrace();
}
}
}
@@ -4,6 +4,7 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import cn.hellohao.utils.Print;
import com.UpYun;
import com.aliyun.oss.OSSClient;
import com.qcloud.cos.COSClient;
@@ -19,6 +20,7 @@ import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import com.upyun.UpException;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -154,6 +156,24 @@ public class ImgServiceImpl implements ImgService {
clientException.printStackTrace();
}
}
//删除FTP存储的图片文件
public void delectFTP(Keys key, String fileName) {
FTPClient ftp = new FTPClient();
String[] host = key.getEndpoint().split("\\:");
String h = host[0];
Integer p = Integer.parseInt(host[1]);
try {
if(!ftp.isConnected()){
ftp.connect(h,p);
}
//如果是需要认证的服务器,就需要账号和密码来登录
ftp.login(key.getAccessKey(), key.getAccessSecret());
ftp.deleteFile(fileName);
} catch (IOException e) {
e.printStackTrace();
Print.warning("删除FTP存储的图片失败");
}
}
@Override
public Integer counts(Integer userid) {
// TODO Auto-generated method stub
+54
View File
@@ -0,0 +1,54 @@
package cn.hellohao.test;
import cn.hellohao.utils.Print;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.io.FileInputStream;
/**
* @author Tiansh
* @version 1.0
* @date 2019/7/29 17:38
* https://blog.csdn.net/WatsonYee/article/details/82389769
*/
public class FTP {
public static void main(String[] args) throws Exception{
//创建FTP客户端,所有的操作都基于FTPClinet
FTPClient ftp = new FTPClient();
//连接FTP服务器
ftp.connect("hellohao.cn",21);
//如果是需要认证的服务器,就需要账号和密码来登录
ftp.login("test", "test");
//获取服务器返回的状态码
int reply = ftp.getReplyCode();
System.out.println(reply);
/*
* 判断是否连接成功
* 所有以2开头的代码是正完成响应。
* FTP服务器将在最终发送一个肯定的完成响应成功完成命令。
*/
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.out.println("连接失败");
return;
}
System.out.println("连接成功");
//返回一个布尔类型的值,来表示是否创建成功
boolean isCreate = ftp.makeDirectory("/ftp");
//设置文件上传类型
ftp.setFileType(ftp.BINARY_FILE_TYPE);
//获取文件的输入流
FileInputStream fis = new FileInputStream("C:\\Users\\tiansh\\Desktop\\11.jpg");
//调用storeFile方法将文件上传到FTP服务器
//第一个参数是上传到服务器的路径,包含了文件名
boolean isUpload = ftp.storeFile("/ftp/upload22.jpg", fis);
boolean isUpload2 = ftp.storeFile("/ftp/upload222.jpg", fis);
Print.warning(isUpload+"=="+isUpload2);
Print.Normal(isUpload);
//设置文件权限
boolean isSet = ftp.sendSiteCommand("chmod 744 " + "/ftp/upload.jpg");
//ftp.deleteFile("/ftp/upload.jpg");
}
}
+18 -22
View File
@@ -1,35 +1,31 @@
package cn.hellohao.test;
import cn.hellohao.utils.Print;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.ftp.Ftp;
import java.io.File;
import java.io.IOException;
public class test1 {
private static void deleteDirectory(File file) {
if (file.isFile()) {// 表示该文件不是文件夹
file.delete();
} else {
// 首先得到当前的路径
String[] childFilePaths = file.list();
for (String childFilePath : childFilePaths) {
String filePath =File.separator + "HellohaoData" + File.separator;
File childFile = new File(filePath + "admin"+ File.separator);
deleteDirectory(childFile);
}
file.delete();
}
}
public static void main(String[] args) {
// Print.warning(System.getProperty("user.dir"));
String str = "[FCAF03D4FDFC22D354FD]";
str = str.replace("[", "");
str = str.replace("]", "");
System.out.println(str);
String[] arr = str.split("&");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
//匿名登录(无需帐号密码的FTP服务器)
Ftp ftp = new Ftp("hellohao.cn");
ftp.init("hellohao.cn",21,"test","test");
//进入远程目录
//ftp.cd("/opt/upload");
//上传本地文件
ftp.upload("/ftp/222222222.jpg", FileUtil.file("C:\\Users\\tiansh\\Desktop\\11.jpg"));
//下载远程文件
//ftp.download("/opt/upload", "test.jpg", FileUtil.file("e:/test2.jpg"));
//关闭连接
try {
ftp.close();
} catch (IOException e) {
e.printStackTrace();
}
@@ -0,0 +1,414 @@
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;
/**
* <p>Title: </p>
* <p>Description: </p>
*
* @author H.Yang
* @QQ 1033542070
* @date 2018年3月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;
}
/**
* <p>Title: 连接服务器</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月10日
*
* @return 连接成功与否 true:成功, false:失败
*/
public boolean open() {
// 判断是否已连接
if (ftpClient != null && ftpClient.isConnected()) {
return true;
}
try {
ftpClient = new FTPClient();
// 连接FTP服务器
ftpClient.connect(this.server, this.port);
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftpClient.login(this.userName, this.userPassword);
// 检测连接是否成功
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
System.out.println("FTP服务器拒绝连接.");
this.close();
System.exit(1);
}
System.out.println("FTP连接成功:" + this.server + ";port:" + this.port + ";name:" + this.userName + ";pwd:" + this.userPassword);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置上传模式.binally or ascii
ftpClient.enterLocalPassiveMode();
return true;
} catch (Exception e) {
this.close();
e.printStackTrace();
return false;
}
}
/**
* <p>Title: 切换到父目录</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月11日
*
* @return 切换结果 true:成功, false:失败
*/
private boolean changeToParentDir() {
try {
return ftpClient.changeToParentDirectory();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* <p>Title: 改变当前目录到指定目录</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月11日
*
* @param dir 目的目录
* @return 切换结果 true:成功,false:失败
*/
private boolean cd(String dir) {
try {
return ftpClient.changeWorkingDirectory(dir);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* <p>Title: 获取目录下所有的文件名称</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月11日
*
* @param filePath 指定的目录
* @return 文件列表,或者null
*/
private FTPFile[] getFileList(String filePath) {
try {
return ftpClient.listFiles(filePath);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* <p>Title: 层层切换工作目录</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月11日
*
* @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;
}
}
/**
* <p>Title: 循环创建目录,并且创建完目录后,设置工作目录为当前创建的目录下</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月11日
*
* @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();
System.out.println("ftpPath:" + ftpPath);
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;
}
}
/**
* <p>Title: 上传文件到FTP服务器</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月11日
*
* @param //localDirectoryAndFileName 本地文件目录和文件名
* @param ftpFileName 上传到服务器的文件名()
* @param ftpDirectory FTP目录如:/path1/pathb2/,如果目录不存在会自动创建目录(目录可以省略)
* @return
*/
//public boolean upload(String localDirectoryAndFileName, String ftpFileName, String ftpDirectory) {
public boolean upload(File srcFile, String ftpFileName, String ftpDirectory) {
if (!ftpClient.isConnected()) {
return false;
}
boolean flag = false;
if (ftpClient != null) {
//File srcFile = new File(localDirectoryAndFileName);
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();
}
}
}
System.out.println("上传文件成功,本地文件名: " + ",上传到目录:" + ftpDirectory + "/" + ftpFileName);
return flag;
}
/**
* <p>Title: 从FTP服务器上下载文件</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月11日
*
* @param ftpDirectoryAndFileName ftp服务器文件路径,以/dir形式开始
* @param localDirectoryAndFileName 保存到本地的目录
* @return
*/
public boolean get(String ftpDirectoryAndFileName, String localDirectoryAndFileName) {
if (!ftpClient.isConnected()) {
return false;
}
ftpClient.enterLocalPassiveMode(); // Use passive mode as default
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
// file
System.out.println(ftpClient.getReplyString()); // check result
System.out.println("从ftp服务器上下载文件:" + ftpDirectoryAndFileName + " 保存到:" + localDirectoryAndFileName);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* <p>Title: 返回FTP目录下的文件列表</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月11日
*
* @param pathName
* @return
*/
public String[] getFileNameList(String pathName) {
try {
return ftpClient.listNames(pathName);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* <p>Title: 删除FTP上的文件</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月11日
*
* @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;
}
}
/**
* <p>Title: 删除FTP目录</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月11日
*
* @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;
}
}
/**
* <p>Title: 关闭链接</p>
* <p>Description: </p>
*
* @author H.Yang
* @date 2018年3月10日
*
*/
public void close() {
try {
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.disconnect();
}
System.out.println("成功关闭连接,服务器ip:" + this.server + ", 端口:" + this.port);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
FTPUtils ftp = new FTPUtils("hellohao.cn", 21, "test", "test");
boolean flag = ftp.open();
if (flag) {
// 上传
//ftp.upload("D:/新建文件夹/1.jpg", "/admin/shihao.jpg", "");
ftp.close();
}
}
}
@@ -41,6 +41,11 @@ public class StringUtils {
&& k.getBucketname()!=null && k.getRequestAddress()!=null ) {
return true;
}
}else if(sourcekey==7){
//FTP
if(k.getEndpoint()!=null && k.getAccessSecret()!=null && k.getEndpoint()!=null && k.getRequestAddress()!=null ) {
return true;
}
}
return false;
}
+3 -3
View File
@@ -1,9 +1,9 @@
#数据库账号
spring.datasource.username=root
spring.datasource.username=picturebed
#数据库密码
spring.datasource.password=root
spring.datasource.password=Aa923453645
#数据库链接地址
spring.datasource.url=jdbc:mysql://localhost:3306/picturebed?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.url=jdbc:mysql://129.28.173.126:3306/picturebed?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
#端口
server.port=8088
#鉴黄周期表达式 下方表达式为每天七点半执行
@@ -2110,7 +2110,7 @@ table.dataTable thead .sorting:after {
border-color: #cfdadd;
border-radius: 2px;
width: 100%;
height: 30px;
/*height: 30px;*/
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
@@ -27,7 +27,7 @@
<hr />
<h3><i class="layui-icon layui-icon-login-qq">&nbsp;</i>开发者交流群:32452345342</h3>
<hr />
<h3><i class="layui-icon layui-icon-auz">&nbsp;</i>当前系统版本:2019-07-25 &nbsp;&nbsp;&nbsp;<a onclick="sysupdate('2019-07-26');" class="layui-btn layui-btn-normal layui-btn-sm">检查更新</a></h3>
<h3><i class="layui-icon layui-icon-auz">&nbsp;</i>当前系统版本:2019-07-26 &nbsp;&nbsp;&nbsp;<a onclick="sysupdate('2019-07-26');" class="layui-btn layui-btn-normal layui-btn-sm">检查更新</a></h3>
<hr />
<h3 style="font-weight: bold;"><i class="layui-icon layui-icon-rmb">&nbsp;</i>支持一下作者吧:</h3>
<br />
@@ -18,13 +18,14 @@
<label class="layui-form-label">对象存储源</label>
<div class="layui-input-block">
<select id="StorageType" name="city" lay-filter="business" lay-verify="required">
<option value="0">未设置任何存储源</option>
<option value="5">本地存储</option>
<option value="1">网易NOS</option>
<option value="2">阿里OSS</option>
<option value="3">又拍USS</option>
<option value="4">七牛云KODO</option>
<option value="6">腾讯COS</option>
<option value="0">&nbsp;未设置任何存储源</option>
<option value="5">&nbsp;本地存储</option>
<option value="1">&nbsp;网易NOS</option>
<option value="2">&nbsp;阿里OSS</option>
<option value="3">&nbsp;又拍USS</option>
<option value="4">&nbsp;七牛云KODO</option>
<option value="6">&nbsp;腾讯COS</option>
<option value="7">&nbsp;FTP存储</option>
</select>
</div>
</div>
@@ -83,7 +84,7 @@
<div class="layui-input-block">
<input id="RequestAddress" type="text" name="title" autocomplete="off" placeholder="生成图片url的域名"
class="layui-input" th:value="${RequestAddress}"/>
<span style="color: #DAA5A6;">需带有http://或https://</span>
<span id="hostsm" style="color: #DAA5A6;">需带有http://或https://</span>
</div>
</div>
@@ -141,11 +142,18 @@
$("#c3-1").css('display','block');
$("#keyusername").text('AccessKey');
$("#keypass").text('SecretKey');
}else if(data.value=6){
}else if(data.value==6){
$("#c3-1").css('display','none');
$("#c3 label").text('地区代码');
$("#keyusername").text('SecretId');
$("#keypass").text('SecretKey');
}else if(data.value==7){
//$("#c3").css('display','none');
$("#c3-1").css('display','none');
$("#c4").css('display','none');
$("#keyusername").text('FTP账号');
$("#keypass").text('FTP密码');
$("#c3 label").text('FTP地址');
}else{
$("#c3").css('display','block');
$("#c3-1").css('display','none');
@@ -167,6 +175,13 @@
}else{
$("#ysm").text("需带有http://或https:");
}
if(data.value==7){
$("#c3 label").text('FTP地址');
$("#ysm").text('按格式填写如127.0.0.1:21不需要添加ftp:// 推荐使用21默认端口,修改过得端口先用xftp等客户端工具测试一下能不能链接。');
}else{
$("#c3 label").text('Endpoint');
$("#ysm").text('需带有http://或https://');
}
$.ajax({
type: "POST",
url: "/admin/root/getkey",
@@ -243,8 +258,14 @@
$("#c3 label").text('地区代码');
$("#keyusername").text('SecretId');
$("#keypass").text('SecretKey');
}
else{
}else if(types==7){
//$("#c3").css('display','none');
$("#c3-1").css('display','none');
$("#c4").css('display','none');
//$("#c3 label").text('地区代码');
$("#keyusername").text('FTP账号');
$("#keypass").text('FTP密码');
}else{
$("#c3").css('display','block');
$("#c3-1").css('display','none');
$("#keyusername").text('AccessKey');
@@ -257,6 +278,14 @@
}else{
$("#ysm").text("需带有http://或https:");
}
if(types==7){
$("#c3 label").text('FTP地址');
$("#ysm").text('按格式填写如127.0.0.1:21不需要添加ftp:// 推荐使用21默认端口,修改过得端口先用xftp等客户端工具测试一下能不能链接。');
}else{
$("#c3 label").text('Endpoint');
$("#ysm").text('需带有http://或https://');
}
});
//保存KEY
@@ -292,7 +321,33 @@
}
}
});
}else{
}else if($("#StorageType").val()==7){
if(AccessKey!="" && AccessSecret!="" &&Endpoint!="" && RequestAddress!="" && StorageType!=""){
$.ajax({
type: "POST",
url: "/admin/root/updatekey",
data: {
AccessKey: AccessKey,
AccessSecret: AccessSecret,
Endpoint: Endpoint,
Bucketname: Bucketname,
RequestAddress: RequestAddress,
StorageType: StorageType
},
dataType: "json",
success: function (data) {
if (data > 0) {
layer.msg("保存成功", {icon: 1});
} else {
layer.msg("保存失败", {icon: 2});
}
}
});
}else{
layer.msg("有参数不正确,请检查", {icon: 2});
}
}
else{
if(AccessKey!="" && AccessSecret!="" &&Endpoint!="" && Bucketname!="" && RequestAddress!="" && StorageType!=""){
$.ajax({
type: "POST",
@@ -190,6 +190,8 @@
str = '本地存储';
}else if (data.source == 6) {
str = '腾云COS';
}else if (data.source == 7) {
str = 'FTP存储';
}else {
str = '未知';
}
+4 -35
View File
@@ -88,6 +88,7 @@
<option value="3">又拍USS</option>
<option value="4">七牛云KODO</option>
<option value="6">腾讯COS</option>
<option value="7">FTP存储</option>
</select>
</div>
<div class="btn-group">
@@ -148,39 +149,6 @@
// 分页
fenye('/admin/selecttable', 1);//1代表查询所有人
// $("#myselect").change(function () {
// var opt = $("#myselect").val();
// // 先销毁table中的数据
// $("#table_server").bootstrapTable('destroy');
// fenye('/admin/selecttable', opt);
// });
//获取本站概况
// $.ajax({
// type: "POST",
// url: "/admin/getwebconfig",
// dataType: "json",
// success: function (data) {
// $("#counts").text(data.counts);
// $("#getusertotal").text(data.getusertotal);
// $("#imgreviewcount").text(data.imgreviewcount);
// $("#usercount").text(data.usercount);
// var str = "";
// if (data.source == 1) {
// str = "网易NOS";
// } else if (data.source == 2) {
// str = "阿里OSS";
// } else if (data.source == 3) {
// str = "又拍USS";
// } else if (data.source == 4) {
// str = '七牛KODO';
// } else {
// str = '未知';
// }
// $("#source").text(str);
// }
// });
});
function screening(){
$("#table_server").bootstrapTable('destroy');
@@ -449,8 +417,9 @@
source = '本地存储';
}else if (rows.source == 6) {
source = '腾讯COS';
}
else {
}else if (rows.source == 7) {
source = 'FTP存储';
}else {
source = '未知';
}
return source;
+5 -2
View File
@@ -234,7 +234,7 @@ Technology constantly updated, we will always move forward on the road ahead.
<!-- full width -->
<div class="col-xs-12 text-center no-pad">
<div class="input-container no-mrg" id="urlstext">
<textarea id="urls" name="message" style="border: 1px solid #838383;border-radius: 5px;"></textarea>
<textarea id="urls" name="message" style="padding:20px;font-weight: 600; border: 1px solid #838383;border-radius: 5px;"></textarea>
<div class="input-border-bottom"></div>
</div>
@@ -333,7 +333,10 @@ Technology constantly updated, we will always move forward on the road ahead.
<p></p>
<div class="form loginBox">
<a href="https://www.maoyuncloud.com/" target="_blank">
<img style="max-width: 33.3%;" src="http://cdn.wwery.com/tourist/4c7810718014927.png" />
<img style="max-width: 33.3%;" src="https://hellohao-cloud.oss-cn-beijing.aliyuncs.com/%E5%AF%B9%E8%B1%A1%E5%AD%98%E5%82%A8%E8%B5%9E%E5%8A%A9logo/WechatIMG172L.png" />
</a>
<a href="https://www.upyun.com" target="_blank">
<img style="max-width: 33.3%;" src="https://hellohao-cloud.oss-cn-beijing.aliyuncs.com/%E5%AF%B9%E8%B1%A1%E5%AD%98%E5%82%A8%E8%B5%9E%E5%8A%A9logo/%E5%8F%88%E6%8B%8D%E4%BA%91_logo2.png" />
</a>
</div>
</div>