这篇文章主要是记录我的FTP文件上传方法和过程
1:配置站点
2:我写的代码目录展示和数据库设置
2.1:代码目录结构
2.2:数据库展示
CREATE TABLE `uploadfile` (
`up_id` int(11) NOT NULL AUTO_INCREMENT,
`up_old_name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '上传文件原名称',
`up_new_name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '上传后文件路径',
`up_type` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '上传文件类型',
`up_time` bigint(20) DEFAULT NULL COMMENT '上传时间',
`up_remarks` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '文件说明',
`res_name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '压缩图片路径or压缩包路径',
PRIMARY KEY (`up_id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
3:配置类展示
3.1:CompressUtil
/**
* 压缩工具类
*/
public class CompressUtil {
/**
* 该方法对于将原图片的宽度设为400,
* 将原图宽度除以400获得系数
* 将原图高度除以400并向上舍入取整获取压缩高度
*
* @param inputStream 输入流
* @return byte
*/
public static byte[] conditionCompress(InputStream inputStream) {
ByteArrayOutputStream os = null;
ByteArrayInputStream srcIs = null;
ByteArrayInputStream thumbnailsIs = null;
try {
os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
//获取到原图片
srcIs = new ByteArrayInputStream(os.toByteArray());
BufferedImage image = ImageIO.read(srcIs);
//获取到原图片的宽度
int srcWidth = image.getWidth();
//获取到原图片的高度
int srcHeight = image.getHeight();
int coefficient = new BigDecimal(srcWidth).divide(new BigDecimal(400), RoundingMode.HALF_UP).intValue();
int desHeight = new BigDecimal(srcHeight).divide(new BigDecimal(coefficient), RoundingMode.HALF_UP).intValue();
thumbnailsIs = new ByteArrayInputStream(os.toByteArray());
os.reset();
Thumbnails.of(thumbnailsIs).size(400, desHeight).keepAspectRatio(false).toOutputStream(os);
return os.toByteArray();
} catch (IOException e) {
return null;
} finally {
if (thumbnailsIs != null)
try {
thumbnailsIs.close();
} catch (IOException ignored) {
}
if (srcIs != null)
try {
srcIs.close();
} catch (IOException ignored) {
}
if (os != null) try {
os.close();
} catch (IOException ignored) {
}
if (inputStream != null)
try {
inputStream.close();
} catch (IOException ignored) {
}
}
}
}
3.2:FtpYmlConfig
@Data
@ConfigurationProperties("ftputil")
public class FtpYmlConfig {
public String localurl;
public String ftpurl;
}
3.3:RedisConfig
@Configuration
public class RedisConfig {
//RedisTemplate模板
@Bean("redisT")
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
//为了开发方便,一般直接使用<String,Object>
RedisTemplate<String,Object> template=new RedisTemplate<>();
template.setConnectionFactory(factory);
//Json序列化配置
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om=new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
//String的序列化
StringRedisSerializer stringRedisSerializer=new StringRedisSerializer();
//key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
//hash的key采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
3.4:SpringMvcConfig
@Configuration
public class SpringMvcConfig extends WebMvcConfigurationSupport {
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setForceEncoding(true);
characterEncodingFilter.setEncoding("utf-8");
registrationBean.setFilter(characterEncodingFilter);
return registrationBean;
}
@Bean
public FilterRegistrationBean repeatedlyReadFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
RepeatedlyReadFilter repeatedlyReadFilter = new RepeatedlyReadFilter();
registration.setFilter(repeatedlyReadFilter);
registration.addUrlPatterns("/*");
return registration;
}
}
4:实体类的展示
4.1:FtpArg(主要用于传输)
@Data
public class FtpArg {
private MultipartFile file;
private String msg;
private String imType;
private String ifZip;
private String zipUrl;
}
4.2:实体类 Uploadfile
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="Uploadfile对象", description="")
public class Uploadfile implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "up_id", type = IdType.AUTO)
@JsonProperty(value = "upId")
private Integer upId;
@ApiModelProperty(value = "上传文件原名称")
@JsonProperty(value = "upOldName")
private String upOldName;
@ApiModelProperty(value = "上传后文件路径")
@JsonProperty(value = "upNewName")
private String upNewName;
@ApiModelProperty(value = "上传文件类型")
@JsonProperty(value = "upType")
private String upType;
@ApiModelProperty(value = "上传时间")
@JsonProperty(value = "upTime")
private Long upTime;
@ApiModelProperty(value = "文件说明")
@JsonProperty(value = "upRemarks")
private String upRemarks;
@ApiModelProperty(value = "压缩图片路径or压缩包路径")
@JsonProperty(value = "resName")
private String resName;
}
5:过滤器和代码生成器就不展示了
6:工具类的展示
6.1:统一返回类R
@Data
public class R {
private String msg;
private Integer code;
private boolean flag;
private Object date;
public static R ok(String msg,Integer code,boolean flag,Object date)
{
R r = new R();
r.setCode(code);
r.setDate(date);
r.setFlag(flag);
r.setMsg(msg);
return r;
}
}
6.2:文件上传根据类:SFtpUtil
@Slf4j
public class SFtpUtil {
private final static Log logger = LogFactory.getLog(SFtpUtil.class);
/**
* 无参构造函数
*/
public SFtpUtil(){
}
/**
* 获取连接对象
* @return
*/
public static FTPClient getFtpClient()
{
FTPClient ftpClient = new FTPClient();
ftpClient.enterLocalPassiveMode();
try{
ftpClient.connect("192.168.5.100",21);
//先连接
if(ftpClient.isConnected())
{
//判断用户是否可以登录
if(ftpClient.login("xieyucan","Ty123456"))
{
//连接完之后,判断是否可用
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))
{
logger.info("FTP连接成功");
logger.info("FTP登录成功,远程地址为{}"+ftpClient.getRemoteAddress());
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
}
}else{
logger.info("连接失败");
ftpClient.disconnect();
}
}
}
catch (SocketException e)
{
e.printStackTrace();
logger.info("FTP的IP地址可能错误,请正确配置。");
}
catch (IOException e)
{
e.printStackTrace();
logger.info("FTP的IP地址可能错误,请正确配置。");
}
return ftpClient;
}
public static void disconnect(FTPClient ftpClient)
{
if(ftpClient.isConnected())
{
try {
ftpClient.disconnect();
log.info("连接已关闭");
} catch (IOException e) {
e.printStackTrace();
log.info("连接关闭失败");
}
}
}
/**
* 上传文件(普通文件上传)
* @param fileName 文件名称
* @param inputStream 输入流
* @param path 传输目标路径
* @return
*/
public static boolean uploadFile(String fileName, InputStream inputStream,String path)
{
FTPClient ftpClient=getFtpClient();
try{
int reply=ftpClient.getReplyCode();
//判断是否有登录成功后返回的回应
if(!FTPReply.isPositiveCompletion(reply))
{
logger.info("登录失败");
return false;
}
//主被动关系
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//判断目录是否存在,不存在则创建
ftpClient.makeDirectory(path);
//切换为要上次的目录
ftpClient.changeWorkingDirectory(path);
//支持中午文件名
fileName=new String(fileName.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING);
//上传文件
logger.info("文件路径{}"+fileName);
//判断是否重复上传,没有的话直接上传文件
if(!ftpClient.storeFile(fileName,inputStream))
{
logger.info("文件{}"+fileName+"已存在");
return false;
}
//关闭输入流
inputStream.close();
ftpClient.logout();
}catch (IOException e){
e.printStackTrace();
}catch (NullPointerException e){
e.printStackTrace();
}finally {
if(ftpClient.isConnected())
{
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
/**
*FTP文件上传
* @param ftpClient 连接对象
* @param target 目标存储目录
* @param inputStream 文件流
* @param saveFile 文件名称
* @param local 目标目录的路劲
* @return
*/
public static boolean upload(FTPClient ftpClient, String target, InputStream inputStream, String saveFile, String local) throws IOException {
try {
String localFile = local + "/" + target;
log.info("目标路劲为{}",target);
//让我的目标路劲改写为支持GBK格式的目录名
String nameUrl = new String(target.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING);
//检查我自己组件的目录是否存在
File file = new File(localFile);
if (!file.exists()) {
boolean mkdirs = file.mkdirs();
log.info("是否需要创建文件{}", mkdirs);
}
//让我上传的文件也支持GBK格式
String nameFile = new String(saveFile.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING);
if (file.exists()) {
if (ftpClient.storeFile(nameUrl + nameFile, inputStream)) {
log.info("文件上传成功");
return true;
} else {
log.info("文件上传失败");
}
} else {
throw new RuntimeException("文件不能包含中文");
}
} catch (IOException e) {
log.error("工作目录不存在");
e.printStackTrace();
} finally {
ftpClient.disconnect();
}
return false;
}
/**
* 删除远程服务器中的文件
* @param ftpClient
* @param url
* @return
*/
public static boolean delFtpFile(FTPClient ftpClient, String url) {
boolean flag = false;
try {
//检查这个目录是否存在
if (ftpClient.changeWorkingDirectory(url)) {
//如果这是一个文件夹,进入目录中,递归删除文件
for (FTPFile file : ftpClient.listFiles()) {
delFtpFile(ftpClient, url + "/" + file.getName());
log.info("路劲{}", url + "/" + new String(file.getName().getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING));
}
}
//如果只是单纯一个文件
if (ftpClient.deleteFile(new String(url.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING))) {
flag = true;
log.info("删除文件");
}
//如果是目录的话,删除结束之后,我顺便把目录也给删除,因为上一步是把目录里面的东西给删除了
if (ftpClient.removeDirectory(new String(url.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING))) {
log.info("目录完整结构已经删除完成");
flag = true;
}
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* 删除本地文件
* @param url
* @return
*/
public static boolean deleteFile(String url) {
File file = new File(url);
//判断他是不是一个文件夹
if (file.isDirectory()) {
for (File file1 : file.listFiles()) {
if (file1.isDirectory()) {
//删除空的文件夹
deleteFile(file.getPath());
}
//删除单个文件
boolean delete = file1.delete();
log.info("删除文件{}是否成功{}", file1.getName(), delete);
}
}
//如果不是文件夹的话
else {
//文件不存在
if (!file.exists()) {
return false;
}
//文件存在
boolean delete = file.delete();
log.info("删除文件{}是否成功{}", file.getName(), delete);
}
if (file.exists()) {
log.info("文件删除失败");
return false;
}
return true;
}
/**
* 解压文件到指定的目录中
* @param zipFile 压缩文件
* @param descDir 解压的目录
* @return
*/
public static boolean unZipFiles(File zipFile,String descDir) throws IOException {
boolean flag=false;
File file=new File(descDir);
if(!file.exists())
{
boolean mkdirs = file.mkdirs();
log.info("创建文件夹{}",mkdirs);
}
//需要修改编码支持中文,否则无法解压
ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
try {
for(Enumeration entries=zip.entries();entries.hasMoreElements();)
{
ZipEntry entry = (ZipEntry) entries.nextElement();
String entryName = entry.getName();
InputStream inputStream = zip.getInputStream(entry);
String outPath = (descDir + "/" + entryName).replaceAll("\\\\", "/");
File file1=new File(outPath.substring(0,outPath.lastIndexOf('/')));
if(!file.exists())
{
file1.mkdirs();
}
//避免他每一次创建同一个文件夹
if(new File(outPath).isDirectory())
{
continue;
}
log.info("输出文件路径信息{}",outPath);
FileOutputStream outputStream = new FileOutputStream(outPath);
byte[]bytes=new byte[1024];
int len;
while((len=inputStream.read(bytes))>0)
{
outputStream.write(bytes,0,len);
}
inputStream.close();
outputStream.close();
flag=true;
}
}catch (Exception e){
e.printStackTrace();
}
return flag;
}
public static void main(String[] args) {
getFtpClient();
}
}
7:服务层UploadfileServiceImpl(这里主要是变更我的上传路径什么的,主要是根据文件上传工具类来传导)
@Slf4j
@Service
public class UploadfileServiceImpl {
@Resource
private UploadfileMapper mapper;
@Resource
private FtpYmlConfig ftpYmlConfig;
public R singleFileUpload(FtpArg ftpArg) {
String oldfileName=null;
String newFileName=null;
Uploadfile uploadfile = new Uploadfile();
boolean success = false;
String a = null;
String b = null;
String c = null;
String MYPATH = null;
String MYPATHZIP = null;
String UNMYPATH = null;
log.info("{}", System.currentTimeMillis());
//判断传入的文件是否为空
if (ftpArg.getFile().isEmpty()) {
return R.ok("文件为空", 104, false, null);
}
//获取上传文件的名字
String fileName = ftpArg.getFile().getOriginalFilename();
log.info("文件的名称为{}",fileName);
oldfileName = fileName;
int end = fileName.lastIndexOf(".");
String subString = fileName.substring(0, end);
//判断是否为压缩文件,这样有利于下面的操作
if (ftpArg.getZipUrl() == null) {
ftpArg.setZipUrl("");
}
if (ftpArg.getIfZip() == null) {
ftpArg.setIfZip("0");
}
//判断是否为图片
log.info("------------------{},{}",ftpArg.getIfZip().equals("0"),ftpArg.getZipUrl().equals(""));
log.info("{}",fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith(".png") || fileName.toLowerCase().endsWith(".tif"));
log.info("111111111111111111111111111111111");
if (fileName != null && (fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith(".png") || fileName.toLowerCase().endsWith(".tif"))) {
//不需要压缩,不指定路径
log.info("------------------{},{}",ftpArg.getIfZip().equals("0"),ftpArg.getZipUrl().equals(""));
if (ftpArg.getIfZip().equals("0") && ftpArg.getZipUrl().equals("")) {
//判断是否为全景图
if (ftpArg.getImType().equals("0")) {
a = "UPPANO/v/";
MYPATH = "/web/hnResource/" + a;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("全景图片");
uploadfile.setUpNewName(a + newFileName);
}
else {
a = "UPIMGS/v" + 10 + "/";
MYPATH = "/web/hnResource/" + a;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("普通图片");
uploadfile.setUpNewName(a + newFileName);
}
//不需要压缩,指定路径
} else if (ftpArg.getIfZip().equals("0") && !(ftpArg.getZipUrl().equals(""))) {
if (ftpArg.getImType().equals("0")) {
a = ftpArg.getZipUrl() + "/";
MYPATH = "/web/hnResource/" + a;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("全景图片");
uploadfile.setUpNewName(a + newFileName);
} else {
a = ftpArg.getZipUrl() + "/";
MYPATH = "/web/hnResource/" + a;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("普通图片");
uploadfile.setUpNewName(a + newFileName);
}
//需要压缩,不指定路劲
} else if (ftpArg.getIfZip().equals("1") && ftpArg.getZipUrl().equals("")) {
if (ftpArg.getImType().equals("0")) {
b = "UPTHUMBNAIL/v/";
MYPATHZIP = "/web/hnResource/" + b;
a = "UPPANO/v/";
MYPATH = "/web/hnResource/" + a;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("全景图片");
uploadfile.setResName(b + fileName);
uploadfile.setUpNewName(a + fileName);
} else {
b = "UPTHUMBNAIL/v" + "/";
MYPATHZIP = "/web/hnResource/" + b;
a = "UPIMGS/v/";
MYPATH = "/web/hnResource/" + a;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("普通图片");
uploadfile.setResName(b + fileName);
uploadfile.setUpNewName(a + fileName);
}
//需要压缩,指定路径
} else if (ftpArg.getIfZip().equals("1") && !(ftpArg.getZipUrl().equals(""))) {
if (ftpArg.getImType().equals("0")) {
b = "UPTHUMBNAIL/v/";
MYPATHZIP = "/web/hnResource/" + b;
a = ftpArg.getZipUrl() + "/";
MYPATH = "/web/hnResource/" + a;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("全景图片");
uploadfile.setResName(b + fileName);
uploadfile.setUpNewName(a + fileName);
} else {
b = "UPTHUMBNAIL/v/";
MYPATHZIP = "/web/hnResource/" + b;
a = ftpArg.getZipUrl() + "/";
MYPATH = "/web/hnResource/" + a;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("普通图片");
uploadfile.setResName(b + fileName);
uploadfile.setUpNewName(a + fileName);
}
}
else {
return R.ok("kon",102,false,null);
}
}
else if (fileName != null && (fileName.toLowerCase().endsWith("pdf") || fileName.toLowerCase().endsWith("doc") || fileName.toLowerCase().endsWith("docx"))) {
//pdf不指定路径
if (ftpArg.getZipUrl() == null || ftpArg.getZipUrl().equals("")) {
ftpArg.setIfZip("0");
a = "UPWORD/v/";
MYPATH = "/web/hnResource/" + a;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("文档");
uploadfile.setUpNewName(a + newFileName);
} else {
ftpArg.setIfZip("0");
a = ftpArg.getZipUrl() + "/";
MYPATH = "/web/hnResource/" + a;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("文档");
uploadfile.setUpNewName(a + newFileName);
}
}
//压缩包
else if (fileName != null && (fileName.toLowerCase().endsWith("zip"))) {
//不指定路劲
if (ftpArg.getZipUrl() == null || ftpArg.getZipUrl().equals("")) {
a = "UPZIP/v/";
MYPATH = "/web/hnResource/" + a;
UNMYPATH = MYPATH;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("压缩文件");
uploadfile.setResName(a + newFileName);
} else {
a = ftpArg.getZipUrl() + "/";
MYPATH = "/web/hnResource/" + a;
c = "UPZIP/v/";
UNMYPATH = "/web/hnResource/" + c;
newFileName = fileName.replace(subString, String.valueOf(System.currentTimeMillis()));
uploadfile.setUpType("压缩文件");
uploadfile.setResName(a + newFileName);
}
}
else {
return R.ok("不支持该文件上传", 104, false, null);
}
try {
//连接ftp
FTPClient ftpClient = SFtpUtil.getFtpClient();
//上传到FTP
//需要压缩,不指定路劲
if (ftpArg.getIfZip().equals("1") && (ftpArg.getZipUrl() == null || ftpArg.getZipUrl().equals(""))) {
success = SFtpUtil.upload(ftpClient, MYPATH, ftpArg.getFile().getInputStream(), newFileName, ftpYmlConfig.getLocalurl());
byte[] bytes = null;
bytes = CompressUtil.conditionCompress(ftpArg.getFile().getInputStream());
//不知道是什么原因,或许是上传一次就需要重新连接FTP吧
ftpClient = SFtpUtil.getFtpClient();
success = SFtpUtil.upload(ftpClient, MYPATHZIP, new ByteArrayInputStream(bytes), newFileName, ftpYmlConfig.getLocalurl());
}
//需要压缩,指定路劲
else if (ftpArg.getIfZip().equals("1") && !(ftpArg.getZipUrl() == null || ftpArg.getZipUrl().equals(""))) {
success = SFtpUtil.upload(ftpClient, MYPATH, ftpArg.getFile().getInputStream(), newFileName, ftpYmlConfig.getLocalurl());
byte[] bytes = null;
bytes = CompressUtil.conditionCompress(ftpArg.getFile().getInputStream());
//不知道是什么原因,或许是上传一次就需要重新连接FTP吧
ftpClient = SFtpUtil.getFtpClient();
success = SFtpUtil.upload(ftpClient, MYPATHZIP, new ByteArrayInputStream(bytes), newFileName, ftpYmlConfig.getLocalurl());
}
//压缩文件,需要解压
else if (fileName.toLowerCase().endsWith("zip")) {
success = SFtpUtil.upload(ftpClient, MYPATH, ftpArg.getFile().getInputStream(), newFileName, ftpYmlConfig.getLocalurl());
Thread.sleep(1000);
if (success) {
//上传成功之后解压文件
File zipFile = new File(ftpYmlConfig.getLocalurl() + MYPATH + newFileName);
String[] split = newFileName.split(".zip");
SFtpUtil.unZipFiles(zipFile, ftpYmlConfig.getLocalurl() + UNMYPATH + split[0]);
}
} else {
success = SFtpUtil.upload(ftpClient, MYPATH, ftpArg.getFile().getInputStream(), newFileName, ftpYmlConfig.getLocalurl());
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
if (success) {
uploadfile.setUpOldName(oldfileName);
uploadfile.setUpTime(System.currentTimeMillis() / 1000);
mapper.insert(uploadfile);
return R.ok("上传成功", 200, true, a + newFileName);
} else {
return R.ok("上传失败", 104, false, null);
}
}
/**
* 工具url删除FTP文件
* @param url
* @return
*/
public R singleFileDelete(String url)
{
log.info("url{}",url);
QueryWrapper<Uploadfile> wrapper = new QueryWrapper<>();
if(url.contains(".zip"))
{
wrapper.eq("res_name",url);
FTPClient ftpClient = SFtpUtil.getFtpClient();
log.info("要删除的路径为{}","/web/hnResource/"+url);
if(SFtpUtil.delFtpFile(ftpClient,"/web/hnResource/"+url))
{
mapper.delete(wrapper);
SFtpUtil.disconnect(ftpClient);
return R.ok("删除成功",200,true,null);
}else {
return R.ok("删除失败",102,false,null);
}
}else{
wrapper.eq("up_new_name", url);
FTPClient ftpClient = SFtpUtil.getFtpClient();
log.info("删除的路径{}","/web/hnResource/"+url);
if(SFtpUtil.delFtpFile(ftpClient,"/web/hnResource/"+url))
{
mapper.delete(wrapper);
SFtpUtil.disconnect(ftpClient);
return R.ok("删除成功",200,true,null);
}else
{
return R.ok("删除失败",102,false,null);
}
}
//return R.ok("删除失败",102,false,null);
}
/**
* 删除本地文件(实现不了)
* @param url
* @return
*/
public R deleteLocalFile(String url)
{
QueryWrapper<Uploadfile> wrapper = new QueryWrapper<>();
if(url.contains(".zip"))
{
wrapper.eq("res_name",url);
if(SFtpUtil.deleteFile(ftpYmlConfig.getLocalurl()+"/web/hnResource/"+url))
{
mapper.delete(wrapper);
return R.ok("删除成功",200,true,null);
}else {
return R.ok("删除失败",102,false,null);
}
}
else {
log.info("要删除的路径为{}:",ftpYmlConfig.getLocalurl()+"/web/hnResource/"+url);
wrapper.eq("up_new_name",url);
if(SFtpUtil.deleteFile(ftpYmlConfig.getLocalurl()+"/web/hnResource/"+url))
{
mapper.delete(wrapper);
return R.ok("删除成功",200,true,null);
}else {
return R.ok("删除失败",102,false,null);
}
}
}
/**
* 根据url查找文件
* @param url
* @return
*/
public R findByFtpUrl(String url) throws IOException {
FTPClient ftpClient = SFtpUtil.getFtpClient();
boolean command = ftpClient.doCommand("opts", "utf8 off");
log.info("这个目前不知道是什么意思{}",command);
//判断是否存在该目录
if(ftpClient.changeWorkingDirectory(new String(("/web/hnResource/"+url).getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING)))
{
List name=new ArrayList();
for(FTPFile file:ftpClient.listFiles())
{
name.add(file.getName());
}
if(name.size()==0)
{
return R.ok("没有文件",200,true,null);
}
return R.ok("查找成功",200,true,name.toString());
}
return R.ok("路径不存在",102,false,null);
}
}
8:controller层
@RestController
@RequestMapping("/upload")
public class UploadfileController {
private final static Log logger = LogFactory.getLog(UploadfileController.class);
@Resource
private UploadfileMapper mapper;
@Resource
private UploadfileServiceImpl service;
/**
* 文件上传FTP
* @param file 打算上传的文件
* @param impType 图片文件类型 0为全景图 1为普通图片
* @param ifZip 是否为缩略图
* @param zipUrl 指定路径
* @return
*/
@PostMapping("/uploadFile")
public R singleFileUpload(@RequestParam(value = "file") MultipartFile file, String impType, String ifZip, String zipUrl) {
FtpArg ftpArg = new FtpArg();
ftpArg.setFile(file);
ftpArg.setIfZip(ifZip);
ftpArg.setZipUrl(zipUrl);
ftpArg.setImType(impType);
return service.singleFileUpload(ftpArg);
}
@PostMapping("/deleteFtpFile")
public R singleFileDeleteFTP(HttpServletRequest request)
{
try {
RequestWrapper requestWrapper= new RequestWrapper(request);
byte[] bytes = StreamUtils.copyToByteArray(requestWrapper.getInputStream());
String body = new String(bytes, requestWrapper.getCharacterEncoding());
JSONObject jsonObject = JSONObject.fromObject(body);
String url = (String) jsonObject.get("url");
return service.singleFileDelete(url);
} catch (Exception e) {
throw new RuntimeException("路径不能为空");
}
}
@PostMapping("/deleteLocalFile")
public R deleteLocalFile(HttpServletRequest request)
{
try {
RequestWrapper requestWrapper=new RequestWrapper(request);
byte[] bytes = StreamUtils.copyToByteArray(requestWrapper.getInputStream());
String body = new String(bytes, requestWrapper.getCharacterEncoding());
JSONObject jsonObject = JSONObject.fromObject(body);
String url = (String) jsonObject.get("url");
return service.deleteLocalFile(url);
} catch (IOException e) {
throw new RuntimeException("路径不能为空");
}
}
@PostMapping("/findByFtpUrl")
public R findByFtpUrl(HttpServletRequest request)
{
try {
RequestWrapper requestWrapper=new RequestWrapper(request);
byte[] bytes = StreamUtils.copyToByteArray(requestWrapper.getInputStream());
String body = new String(bytes, requestWrapper.getCharacterEncoding());
JSONObject jsonObject = JSONObject.fromObject(body);
String url = (String) jsonObject.get("url");
return service.findByFtpUrl(url);
} catch (IOException e) {
throw new RuntimeException("该路径不存在");
}
}
}
9:yml文件
spring:
datasource:
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/friend?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mybatis:
type-aliases-package: com.example.document.entity
mapper-locations: classpath:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
ftputil:
ip: 192.168.5.100
port: 21
username: xieyucan
password: Ty123456
localurl: C:\Users\admin\Desktop\FTP
ftpurl: http://192.168.5.98/api/
10:pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>document</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>document</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- MybatisPush -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!--swagger2 依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!--zip-->
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.7.0</version>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--导入spring boot 整合Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--配置redis连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- 压缩-->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<dependency>
<groupId>io.cloudsoft.windows</groupId>
<artifactId>winrm4j</artifactId>
<version>0.5.0</version> <!-- WINRM4J_VERSION -->
</dependency>
<!-- FTP上传文件依赖 -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier> <!-- 需要指定JDK版本哦:2.4有13,15两个JDK版本 -->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>