Explorar el Código

update:图片上传优化v1

lvzhiqiang hace 1 año
padre
commit
5b576e0872

+ 6 - 0
pom.xml

@@ -154,6 +154,12 @@
             <artifactId>commons-net</artifactId>
             <version>3.10.0</version>
         </dependency>
+        <!-- Thumbnailator Dependency -->
+        <dependency>
+            <groupId>net.coobird</groupId>
+            <artifactId>thumbnailator</artifactId>
+            <version>0.4.18</version>
+        </dependency>
 
         <!--redis-->
         <dependency>

+ 0 - 140
src/main/java/top/lvzhiqiang/controller/CoinController.java

@@ -2,12 +2,9 @@ package top.lvzhiqiang.controller;
 
 import com.alibaba.fastjson.JSONObject;
 import org.springframework.web.bind.annotation.*;
-import org.springframework.web.multipart.MultipartFile;
-import top.lvzhiqiang.config.InitRunner;
 import top.lvzhiqiang.dto.R;
 import top.lvzhiqiang.entity.CoinApiConfig;
 import top.lvzhiqiang.entity.CoinWatchlist;
-import top.lvzhiqiang.entity.FileImage;
 import top.lvzhiqiang.enumeration.ResultCodeEnum;
 import top.lvzhiqiang.exception.BusinessException;
 import top.lvzhiqiang.exception.ParameterException;
@@ -16,14 +13,9 @@ import top.lvzhiqiang.service.CoinApiConfigService;
 import top.lvzhiqiang.service.CoinService;
 import top.lvzhiqiang.service.impl.CoinServiceImpl;
 import top.lvzhiqiang.util.DateUtils;
-import top.lvzhiqiang.util.FtpUtil;
 import top.lvzhiqiang.util.StringUtils;
 
 import javax.annotation.Resource;
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigDecimal;
-import java.math.RoundingMode;
 import java.time.LocalDate;
 import java.util.List;
 
@@ -122,138 +114,6 @@ public class CoinController {
     }
 
     /**
-     * 上传图片
-     *
-     * @author lvzhiqiang
-     * 2023/12/29 10:26
-     */
-    @RequestMapping("/InsertOrUpdateImg")
-    @ResponseBody
-    public R InsertOrUpdateImg(@RequestParam("file") MultipartFile file, String remark, Long categoryId, String id) {
-        if (StringUtils.isEmpty(id) && (file == null || file.getSize() == 0)) {
-            throw new ParameterException("文件为空!");
-        }
-
-        if (categoryId == null) {
-            throw new ParameterException("categoryId为空!");
-        }
-
-        String imageUrl = "";
-        String imageSize = "";
-        if (StringUtils.isEmpty(id)) {
-            try {
-                // 1、给上传的图片生成新的文件名
-                // 1.1获取原始文件名
-                String oldName = file.getOriginalFilename();
-                // 1.2使用FtpUtil工具类生成新的文件名,新文件名 = newName + 文件后缀
-                String newName = FtpUtil.genImageName();
-                newName = newName + oldName.substring(oldName.lastIndexOf("."));
-
-                // 2、把图片上传到图片服务器
-                // 2.1获取上传的io流
-                InputStream input = file.getInputStream();
-                // 2.2调用FtpUtil工具类进行上传
-                boolean result = FtpUtil.uploadFile(newName, input);
-                if (result) {
-                    //返回给前端图片访问路径
-                    imageUrl = LocalDate.now().format(DateUtils.dateFormatter_) + "/" + newName;
-                    imageSize = BigDecimal.valueOf(file.getSize()).divide(new BigDecimal("1024")).setScale(0, RoundingMode.UP).toPlainString().concat("KB");
-
-                    FileImage fileImage = new FileImage();
-                    fileImage.setOldName(oldName);
-                    fileImage.setNewName(newName);
-                    fileImage.setSize(imageSize);
-                    fileImage.setPath(imageUrl);
-                    fileImage.setRemark(remark);
-                    fileImage.setCategoryId(categoryId);
-                    coinMapper.insertFileImage(fileImage);
-                }
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-
-            JSONObject result = new JSONObject();
-            result.put("imageUrl", FtpUtil.getBaseUrl() + imageUrl);
-            result.put("imageSize", imageSize);
-
-            return R.ok().data(result);
-        } else {
-            FileImage fileImage = coinMapper.findFileImageById(Long.valueOf(id));
-            if (fileImage == null) {
-                throw new BusinessException(ResultCodeEnum.UNKNOWN_ERROR.getCode(), "ID 不存在!");
-            }
-
-            fileImage.setCategoryId(categoryId);
-            if (StringUtils.isNotEmpty(remark)) {
-                fileImage.setRemark(remark);
-            }
-
-            if (file != null && file.getSize() > 0) {
-                try {
-                    String ftpBasePath = InitRunner.dicCodeMap.get("ftp_basepath").getCodeValue();
-                    boolean flag = FtpUtil.delFile(ftpBasePath + fileImage.getPath());
-                    if (flag) {
-                        String oldName = file.getOriginalFilename();
-                        String newName = FtpUtil.genImageName();
-                        newName = newName + oldName.substring(oldName.lastIndexOf("."));
-                        InputStream input = file.getInputStream();
-                        // 2.2调用FtpUtil工具类进行上传
-                        boolean result = FtpUtil.uploadFile(newName, input);
-                        if (result) {
-                            imageUrl = LocalDate.now().format(DateUtils.dateFormatter_) + "/" + newName;
-                            imageSize = BigDecimal.valueOf(file.getSize()).divide(new BigDecimal("1024")).setScale(0, RoundingMode.UP).toPlainString().concat("KB");
-
-                            fileImage.setOldName(oldName);
-                            fileImage.setNewName(newName);
-                            fileImage.setSize(imageSize);
-                            fileImage.setPath(imageUrl);
-                        } else {
-                            throw new BusinessException(ResultCodeEnum.UNKNOWN_ERROR.getCode(), "上传新文件失败!");
-                        }
-
-                    } else {
-                        throw new BusinessException(ResultCodeEnum.UNKNOWN_ERROR.getCode(), "删除旧文件失败!");
-                    }
-                } catch (Exception e) {
-                    e.printStackTrace();
-                    return R.error().message(e.getMessage());
-                }
-            }
-
-            coinMapper.updateFileImage(fileImage);
-            return R.ok().data("success");
-        }
-    }
-
-    @RequestMapping("/deleteImgs/{imageId}")
-    @ResponseBody
-    public R deleteImgs(@PathVariable Long imageId) {
-        if (imageId == null) {
-            throw new ParameterException("imageId为空!");
-        }
-
-        FileImage fileImage = coinMapper.findFileImageById(imageId);
-        if (fileImage == null) {
-            throw new BusinessException(ResultCodeEnum.UNKNOWN_ERROR.getCode(), "ID 不存在!");
-        }
-
-        try {
-            String ftpBasePath = InitRunner.dicCodeMap.get("ftp_basepath").getCodeValue();
-            boolean flag = FtpUtil.delFile(ftpBasePath + fileImage.getPath());
-
-            if (flag) {
-                coinMapper.deleteFileImageById(imageId);
-                return R.ok();
-            } else {
-                return R.error().message("删除失败");
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-            return R.error().message(e.getMessage());
-        }
-    }
-
-    /**
      * insertOrUpdateWatchlist
      *
      * @author lvzhiqiang

+ 35 - 4
src/main/java/top/lvzhiqiang/controller/PictureInfoController.java

@@ -2,13 +2,14 @@ package top.lvzhiqiang.controller;
 
 import com.alibaba.fastjson.JSON;
 import com.github.pagehelper.PageInfo;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+import top.lvzhiqiang.dto.R;
 import top.lvzhiqiang.dto.VideoInfoQuery;
 import top.lvzhiqiang.entity.FileImage;
+import top.lvzhiqiang.exception.ParameterException;
 import top.lvzhiqiang.service.PictureInfoService;
+import top.lvzhiqiang.util.StringUtils;
 
 import javax.annotation.Resource;
 import java.util.HashMap;
@@ -38,4 +39,34 @@ public class PictureInfoController {
     public PageInfo<FileImage> getPictureInfoPage(@RequestBody VideoInfoQuery videoInfoQuery) {
         return pictureInfoService.getPictureInfoPage(JSON.parseObject(JSON.toJSONString(videoInfoQuery), HashMap.class));
     }
+
+    /**
+     * 上传图片
+     *
+     * @author lvzhiqiang
+     * 2023/12/29 10:26
+     */
+    @RequestMapping("/insertOrUpdateImg")
+    @ResponseBody
+    public R insertOrUpdateImg(@RequestParam("file") MultipartFile file, String remark, Long categoryId, String id) {
+        if (StringUtils.isEmpty(id) && (file == null || file.getSize() == 0)) {
+            throw new ParameterException("文件为空!");
+        }
+
+        if (categoryId == null) {
+            throw new ParameterException("categoryId为空!");
+        }
+
+        return pictureInfoService.insertOrUpdateImg(file, remark, categoryId, id);
+    }
+
+    @RequestMapping("/deleteImgs/{imageId}")
+    @ResponseBody
+    public R deleteImgs(@PathVariable Long imageId) {
+        if (imageId == null) {
+            throw new ParameterException("imageId为空!");
+        }
+
+        return pictureInfoService.deleteImgs(imageId);
+    }
 }

+ 1 - 0
src/main/java/top/lvzhiqiang/entity/FileImage.java

@@ -39,6 +39,7 @@ public class FileImage implements Serializable {
      * 图片路径
      */
     private String path;
+    private String thumbnailPath;
 
     /**
      * 备注

+ 0 - 25
src/main/java/top/lvzhiqiang/mapper/CoinMapper.java

@@ -182,31 +182,6 @@ public interface CoinMapper {
     @Select("select * from coin_watchlist where symbol = #{symbol} and delete_flag = 1")
     CoinWatchlist findWatchlistBySymbol(String symbol);
 
-    @Insert("INSERT INTO file_image(old_name, new_name, category_id, size, path, remark, create_time, modify_time) " +
-            "VALUES (#{oldName}, #{newName}, #{categoryId}, #{size}, #{path}, #{remark}, now(), now())")
-    int insertFileImage(FileImage fileImage);
-
-    @Update("update file_image set old_name=#{oldName},new_name=#{newName},category_id=#{categoryId},size=#{size},path=#{path},remark=#{remark},modify_time=now() where id=#{id}")
-    int updateFileImage(FileImage fileImage);
-
-    @Select({"<script>" +
-            "select a.*,b.category_name from file_image a left join file_image_category b on a.category_id = b.id WHERE a.delete_flag = 1" +
-            "<if test=\"keyword != null and keyword != ''\">" +
-            "   and (a.old_name like concat('%',#{keyword},'%') or a.remark like concat('%',#{keyword},'%'))" +
-            "</if>" +
-            "<if test=\"categoryField != null and categoryField != ''\">" +
-            "   and a.category_id = #{categoryField}" +
-            "</if>" +
-            " order by ${sortField} ${sort}" +
-            "</script>"})
-    List<FileImage> findImageList(Map<String, Object> params);
-
-    @Select("select * from file_image where id = #{id}")
-    FileImage findFileImageById(Long id);
-
-    @Select("delete from file_image where id = #{id}")
-    FileImage deleteFileImageById(Long id);
-
     @Insert({"<script>" +
             "INSERT INTO coin_cmc_map(cmc_id,cmc_rank,name,symbol,slug,is_active,status," +
             "first_historical_data,last_historical_data,platform,modify_time)" +

+ 28 - 0
src/main/java/top/lvzhiqiang/mapper/PictureInfoMapper.java

@@ -1,6 +1,8 @@
 package top.lvzhiqiang.mapper;
 
+import org.apache.ibatis.annotations.Insert;
 import org.apache.ibatis.annotations.Select;
+import org.apache.ibatis.annotations.Update;
 import top.lvzhiqiang.entity.FileImage;
 import top.lvzhiqiang.entity.VideoCast;
 import top.lvzhiqiang.entity.VideoGenres;
@@ -37,4 +39,30 @@ public interface PictureInfoMapper {
             "</if>" +
             "</script>"})
     List<FileImage> getUploadImageInfoList(Map<String, Object> params);
+
+    @Insert("INSERT INTO file_image(old_name, new_name, category_id, size, path, remark, create_time, modify_time) " +
+            "VALUES (#{oldName}, #{newName}, #{categoryId}, #{size}, #{path}, #{remark}, now(), now())")
+    int insertFileImage(FileImage fileImage);
+
+    @Update("update file_image set old_name=#{oldName},new_name=#{newName},category_id=#{categoryId},size=#{size},path=#{path},remark=#{remark},modify_time=now() where id=#{id}")
+    int updateFileImage(FileImage fileImage);
+
+    @Select({"<script>" +
+            "select a.*,b.category_name from file_image a left join file_image_category b on a.category_id = b.id WHERE a.delete_flag = 1" +
+            "<if test=\"keyword != null and keyword != ''\">" +
+            "   and (a.old_name like concat('%',#{keyword},'%') or a.remark like concat('%',#{keyword},'%'))" +
+            "</if>" +
+            "<if test=\"categoryField != null and categoryField != ''\">" +
+            "   and a.category_id = #{categoryField}" +
+            "</if>" +
+            " order by ${sortField} ${sort}" +
+            "</script>"})
+    List<FileImage> findImageList(Map<String, Object> params);
+
+    @Select("select * from file_image where id = #{id}")
+    FileImage findFileImageById(Long id);
+
+    @Select("delete from file_image where id = #{id}")
+    FileImage deleteFileImageById(Long id);
+
 }

+ 6 - 0
src/main/java/top/lvzhiqiang/service/PictureInfoService.java

@@ -1,6 +1,8 @@
 package top.lvzhiqiang.service;
 
 import com.github.pagehelper.PageInfo;
+import org.springframework.web.multipart.MultipartFile;
+import top.lvzhiqiang.dto.R;
 import top.lvzhiqiang.entity.FileImage;
 
 import java.util.Map;
@@ -18,4 +20,8 @@ public interface PictureInfoService {
      * @return
      */
     PageInfo<FileImage> getPictureInfoPage(Map<String, Object> params);
+
+    R insertOrUpdateImg(MultipartFile file, String remark, Long categoryId, String id);
+
+    R deleteImgs(Long imageId);
 }

+ 11 - 3
src/main/java/top/lvzhiqiang/service/impl/CoinServiceImpl.java

@@ -28,6 +28,7 @@ import top.lvzhiqiang.entity.*;
 import top.lvzhiqiang.exception.BusinessException;
 import top.lvzhiqiang.mapper.CoinApiConfigMapper;
 import top.lvzhiqiang.mapper.CoinMapper;
+import top.lvzhiqiang.mapper.PictureInfoMapper;
 import top.lvzhiqiang.service.CoinService;
 import top.lvzhiqiang.util.*;
 
@@ -109,6 +110,9 @@ public class CoinServiceImpl implements CoinService {
     private CoinApiConfigMapper coinApiConfigMapper;
 
     @Resource
+    private PictureInfoMapper pictureInfoMapper;
+
+    @Resource
     private RedissonClient redissonClient;
 
     @Resource
@@ -1537,7 +1541,7 @@ public class CoinServiceImpl implements CoinService {
             return watchlistPageInfo;
         } else if (params.getString("nameEn").equals("image")) {
             PageHelper.startPage(params.getInteger("pageNo"), params.getInteger("pageSize"), true);
-            List<FileImage> fileImageList = coinMapper.findImageList(params.toJavaObject(Map.class));
+            List<FileImage> fileImageList = pictureInfoMapper.findImageList(params.toJavaObject(Map.class));
 
             PageInfo<FileImage> imagePageInfo = new PageInfo<>(fileImageList);
 
@@ -2146,10 +2150,14 @@ public class CoinServiceImpl implements CoinService {
     @Override
     public Object mainSearchDetail(String nameEn, String id) {
         if ("image".equals(nameEn)) {
-            FileImage fileImage = coinMapper.findFileImageById(Long.valueOf(id));
+            FileImage fileImage = pictureInfoMapper.findFileImageById(Long.valueOf(id));
 
             String ftpBaseurl = InitRunner.dicCodeMap.get("ftp_baseurl").getCodeValue();
-            fileImage.setPath(ftpBaseurl + fileImage.getPath());
+            String ftpBasePath = InitRunner.dicCodeMap.get("ftp_basepath").getCodeValue();
+            String ftpThumbnailBasePath = InitRunner.dicCodeMap.get("ftp_thumbnail_basepath").getCodeValue();
+            String path = fileImage.getPath();
+            fileImage.setPath(ftpBaseurl + ftpBasePath + path);
+            fileImage.setThumbnailPath(ftpBaseurl + ftpThumbnailBasePath + path);
             return fileImage;
         } else if ("watchlist".equals(nameEn)) {
             CoinWatchlist coinWatchlist = coinMapper.findWatchlistBySymbol(id);

+ 156 - 1
src/main/java/top/lvzhiqiang/service/impl/PictureInfoServiceImpl.java

@@ -1,14 +1,33 @@
 package top.lvzhiqiang.service.impl;
 
+import com.alibaba.fastjson.JSONObject;
 import com.github.pagehelper.PageInfo;
+import lombok.extern.slf4j.Slf4j;
+import net.coobird.thumbnailator.Thumbnails;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
 import top.lvzhiqiang.config.InitRunner;
+import top.lvzhiqiang.dto.R;
 import top.lvzhiqiang.entity.FileImage;
+import top.lvzhiqiang.enumeration.ResultCodeEnum;
+import top.lvzhiqiang.exception.BusinessException;
 import top.lvzhiqiang.mapper.PictureInfoMapper;
 import top.lvzhiqiang.service.PictureInfoService;
+import top.lvzhiqiang.util.DateUtils;
+import top.lvzhiqiang.util.FtpUtil;
+import top.lvzhiqiang.util.StringUtils;
 
 import javax.annotation.Resource;
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.time.LocalDate;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
@@ -20,6 +39,7 @@ import java.util.Map;
  * 2024/8/26 11:02
  */
 @Service
+@Slf4j
 public class PictureInfoServiceImpl extends BaseServiceImpl<Object> implements PictureInfoService {
 
     @Resource
@@ -43,8 +63,12 @@ public class PictureInfoServiceImpl extends BaseServiceImpl<Object> implements P
             pictureInfoList = pictureInfoMapper.getUploadImageInfoList(params);
 
             String bpicsUrl = InitRunner.dicCodeMap.get("bpics_url").getCodeValue();
+            String ftpBasePath = InitRunner.dicCodeMap.get("ftp_basepath").getCodeValue();
+            String ftpThumbnailBasePath = InitRunner.dicCodeMap.get("ftp_thumbnail_basepath").getCodeValue();
             pictureInfoList.stream().forEach(e -> {
-                e.setPath(bpicsUrl + e.getPath());
+                String path = e.getPath();
+                e.setPath(bpicsUrl + ftpBasePath + path);
+                e.setThumbnailPath(bpicsUrl + ftpThumbnailBasePath + path);
             });
         }
 
@@ -52,4 +76,135 @@ public class PictureInfoServiceImpl extends BaseServiceImpl<Object> implements P
         return pictureInfoPageInfo;
     }
 
+    @Override
+    public R insertOrUpdateImg(MultipartFile file, String remark, Long categoryId, String id) {
+        String imageUrl = "";
+        String imageSize = "";
+        String ftpBasePath = InitRunner.dicCodeMap.get("ftp_basepath").getCodeValue();
+        String ftpThumbnailBasePath = InitRunner.dicCodeMap.get("ftp_thumbnail_basepath").getCodeValue();
+        String ftpBaseUrl = InitRunner.dicCodeMap.get("ftp_baseurl").getCodeValue();
+        String parentPath = LocalDate.now().format(DateUtils.dateFormatter5);
+        if (StringUtils.isEmpty(id)) {
+            try {
+                // 1、给上传的图片生成新的文件名
+                // 1.1获取原始文件名
+                String oldName = file.getOriginalFilename();
+                // 1.2使用FtpUtil工具类生成新的文件名,新文件名 = newName + 文件后缀
+                String newName = FtpUtil.genImageName();
+                newName = newName + oldName.substring(oldName.lastIndexOf("."));
+
+                // 2、把图片上传到图片服务器
+                // 2.1获取上传的io流
+                InputStream input = file.getInputStream();
+                // 2.2调用FtpUtil工具类进行上传
+                boolean result = FtpUtil.uploadFile(ftpBasePath, parentPath, newName, input);
+                // 2.3缩略图
+                BufferedImage originalImage = ImageIO.read(file.getInputStream());
+                BufferedImage thumbnailImage = Thumbnails.of(originalImage).size(300, 200).asBufferedImage();
+                ByteArrayOutputStream thumbnailOutputStream = new ByteArrayOutputStream();
+                ImageIO.write(thumbnailImage, "jpg", thumbnailOutputStream);
+                ByteArrayInputStream thumbnailInputStream = new ByteArrayInputStream(thumbnailOutputStream.toByteArray());
+                FtpUtil.uploadFile(ftpThumbnailBasePath, parentPath, newName, thumbnailInputStream);
+                if (result) {
+                    //返回给前端图片访问路径
+                    imageUrl = parentPath + "/" + newName;
+                    imageSize = BigDecimal.valueOf(file.getSize()).divide(new BigDecimal("1024")).setScale(0, RoundingMode.UP).toPlainString().concat("KB");
+
+                    FileImage fileImage = new FileImage();
+                    fileImage.setOldName(oldName);
+                    fileImage.setNewName(newName);
+                    fileImage.setSize(imageSize);
+                    fileImage.setPath(imageUrl);
+                    fileImage.setRemark(remark);
+                    fileImage.setCategoryId(categoryId);
+                    pictureInfoMapper.insertFileImage(fileImage);
+                }
+            } catch (IOException e) {
+                log.error("insertOrUpdateImg Exception,", e);
+            }
+
+            JSONObject result = new JSONObject();
+            result.put("imageUrl", ftpBaseUrl + ftpBasePath + imageUrl);
+            result.put("imageSize", imageSize);
+
+            return R.ok().data(result);
+        } else {
+            FileImage fileImage = pictureInfoMapper.findFileImageById(Long.valueOf(id));
+            if (fileImage == null) {
+                throw new BusinessException(ResultCodeEnum.UNKNOWN_ERROR.getCode(), "ID 不存在!");
+            }
+
+            fileImage.setCategoryId(categoryId);
+            if (StringUtils.isNotEmpty(remark)) {
+                fileImage.setRemark(remark);
+            }
+
+            if (file != null && file.getSize() > 0) {
+                try {
+                    boolean flag = FtpUtil.delFile(ftpBasePath + fileImage.getPath());
+                    FtpUtil.delFile(ftpThumbnailBasePath + fileImage.getPath());
+                    if (flag) {
+                        String oldName = file.getOriginalFilename();
+                        String newName = FtpUtil.genImageName();
+                        newName = newName + oldName.substring(oldName.lastIndexOf("."));
+                        InputStream input = file.getInputStream();
+                        // 2.2调用FtpUtil工具类进行上传
+                        boolean result = FtpUtil.uploadFile(ftpBasePath, parentPath, newName, input);
+                        // 2.3缩略图
+                        BufferedImage originalImage = ImageIO.read(file.getInputStream());
+                        BufferedImage thumbnailImage = Thumbnails.of(originalImage).size(300, 200).asBufferedImage();
+                        ByteArrayOutputStream thumbnailOutputStream = new ByteArrayOutputStream();
+                        ImageIO.write(thumbnailImage, "jpg", thumbnailOutputStream);
+                        ByteArrayInputStream thumbnailInputStream = new ByteArrayInputStream(thumbnailOutputStream.toByteArray());
+                        FtpUtil.uploadFile(ftpThumbnailBasePath, parentPath, newName, thumbnailInputStream);
+                        if (result) {
+                            imageUrl = parentPath + "/" + newName;
+                            imageSize = BigDecimal.valueOf(file.getSize()).divide(new BigDecimal("1024")).setScale(0, RoundingMode.UP).toPlainString().concat("KB");
+
+                            fileImage.setOldName(oldName);
+                            fileImage.setNewName(newName);
+                            fileImage.setSize(imageSize);
+                            fileImage.setPath(imageUrl);
+                        } else {
+                            throw new BusinessException(ResultCodeEnum.UNKNOWN_ERROR.getCode(), "上传新文件失败!");
+                        }
+
+                    } else {
+                        throw new BusinessException(ResultCodeEnum.UNKNOWN_ERROR.getCode(), "删除旧文件失败!");
+                    }
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    return R.error().message(e.getMessage());
+                }
+            }
+
+            pictureInfoMapper.updateFileImage(fileImage);
+            return R.ok().data("success");
+        }
+    }
+
+    @Override
+    public R deleteImgs(Long imageId) {
+        FileImage fileImage = pictureInfoMapper.findFileImageById(imageId);
+        if (fileImage == null) {
+            throw new BusinessException(ResultCodeEnum.UNKNOWN_ERROR.getCode(), "ID 不存在!");
+        }
+
+        try {
+            String ftpBasePath = InitRunner.dicCodeMap.get("ftp_basepath").getCodeValue();
+            String ftpThumbnailBasePath = InitRunner.dicCodeMap.get("ftp_thumbnail_basepath").getCodeValue();
+            boolean flag = FtpUtil.delFile(ftpBasePath + fileImage.getPath());
+            FtpUtil.delFile(ftpThumbnailBasePath + fileImage.getPath());
+            if (flag) {
+                pictureInfoMapper.deleteFileImageById(imageId);
+                return R.ok();
+            } else {
+                return R.error().message("删除失败");
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            return R.error().message(e.getMessage());
+        }
+    }
+
 }

+ 3 - 0
src/main/java/top/lvzhiqiang/util/DateUtils.java

@@ -40,6 +40,8 @@ public class DateUtils {
     public static final String PATTERN_TO_DAYS3 = "yyyy年M月d日";
     public static final String PATTERN_TO_DAYS4 = "yyyy/M/d";
 
+    public static final String PATTERN_TO_DAYS5 = "yyyy/MM/dd";
+
     /**
      * (精确到秒的)日期样式
      */
@@ -51,6 +53,7 @@ public class DateUtils {
     public static final DateTimeFormatter dateFormatter2 = DateTimeFormatter.ofPattern(PATTERN_TO_DAYS2);
     public static final DateTimeFormatter dateFormatter3 = DateTimeFormatter.ofPattern(PATTERN_TO_DAYS3);
     public static final DateTimeFormatter dateFormatter4 = DateTimeFormatter.ofPattern(PATTERN_TO_DAYS4);
+    public static final DateTimeFormatter dateFormatter5 = DateTimeFormatter.ofPattern(PATTERN_TO_DAYS5);
 
     public static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(PATTERN_TO_SECONDS);
     public static final DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern(PATTERN_TO_MINUTES);

+ 20 - 2
src/main/java/top/lvzhiqiang/util/FtpUtil.java

@@ -41,6 +41,10 @@ public class FtpUtil {
         baseUrl = baseUrl_;
     }
 
+    public static boolean uploadFile(String fileName, InputStream input) {
+        return uploadFile(basePath, LocalDate.now().format(DateUtils.dateFormatter_), fileName, input);
+    }
+
     /**
      * Description: 向FTP服务器上传文件
      *
@@ -48,7 +52,7 @@ public class FtpUtil {
      * @param input    输入流
      * @return 成功返回true,否则返回false
      */
-    public static boolean uploadFile(String fileName, InputStream input) {
+    public static boolean uploadFile(String rootPath, String parentPath, String fileName, InputStream input) {
         FTPClient ftpClient = null;
         boolean flag = false;
         try {
@@ -59,7 +63,7 @@ public class FtpUtil {
             // 设置上传文件的类型为二进制类型
             ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
             // 设置存储图片的文件夹
-            String workingDirectory = basePath.concat(LocalDate.now().format(DateUtils.dateFormatter_));
+            String workingDirectory = rootPath.concat(parentPath);
             String[] split = workingDirectory.split("/");
             for (String s : split) {
                 if (StringUtils.isEmpty(s)) {
@@ -108,8 +112,22 @@ public class FtpUtil {
         try {
             ftpClient = genFtpClient();
 
+            // 设置为被动模式
+            ftpClient.enterLocalPassiveMode();
+
             // 删除文件
             flag = ftpClient.deleteFile(filePath);
+
+            String parentDirectory = ftpClient.printWorkingDirectory() + File.separator + filePath;
+            while (true) {
+                parentDirectory = parentDirectory.substring(0, parentDirectory.lastIndexOf("/"));
+                FTPFile[] files = ftpClient.listFiles(parentDirectory);
+                if (files.length == 0) {
+                    ftpClient.removeDirectory(parentDirectory);
+                } else {
+                    break;
+                }
+            }
         } catch (SocketException e) {
             log.error("文件删除-连接错误,filePath={}", filePath, e);
         } catch (Exception e) {

+ 1 - 1
src/main/resources/static/coin.html

@@ -434,7 +434,7 @@
             <div class="uploadImgs-loading"><img src='cover/loading.gif'></div>
             <span class="font">InsertOrUpdateImg</span>
             <span id="uploadImgsAlert" style="margin-left: 10px;font-size: 13px;"></span>
-            <form method="post" action="coin/InsertOrUpdateImg" enctype="multipart/form-data" onsubmit="return false;" id="uploadImgs">
+            <form method="post" action="pictureInfo/insertOrUpdateImg" enctype="multipart/form-data" onsubmit="return false;" id="uploadImgs">
                 <span>ID</span>
                 <input type="text" name="id" placeholder="可为空"/>
                 <span>分类</span>

+ 2 - 2
src/main/resources/static/js/my-coin.js

@@ -576,7 +576,7 @@ function initContentEvent(nameEn) {
         $(".apis-quiet-div-image-delete").click(function () {
             var symbol = $(this).attr("symbolName");
             $.ajax({
-                url: "coin/deleteImgs/" + symbol, //请求的url地址
+                url: "pictureInfo/deleteImgs/" + symbol, //请求的url地址
                 type: "get", //请求方式
                 async: true, //请求是否异步,默认为异步,这也是ajax重要特性
                 success: function (data) {
@@ -616,7 +616,7 @@ function initContentEvent(nameEn) {
 function uploadImgsSubmit(){
     var fromData = new FormData($("#uploadImgs")[0]);
     $.ajax({
-        url: "coin/InsertOrUpdateImg", //请求的url地址
+        url: "pictureInfo/insertOrUpdateImg", //请求的url地址
         dataType: "json", //返回格式为json
         data: fromData, //参数值
         type: "post", //请求方式

+ 1 - 1
src/main/resources/static/js/my-picture.js

@@ -142,7 +142,7 @@ function search(pageNo, startFlag, searchSelectFlag) {
 
                     str += "<li class=\"col-lg-8 col-md-6 col-sm-4 col-xs-3\">" +
                         "   <div class=\"myui-vodlist__box\">" +
-                        "       <a class=\"myui-vodlist__thumb lazyload\" title=\"\" style=\"background-image: url(&quot;" + picInfo.path + "&quot;);\">" +
+                        "       <a class=\"myui-vodlist__thumb lazyload\" title=\"\" style=\"background-image: url(&quot;" + picInfo.thumbnailPath + "&quot;),url(&quot;" + picInfo.path + "&quot;);\">" +
                         "           <span class=\"bigpreview playvideo play hidden-xs\" imgUrl='" + picInfo.path + "'></span>" +
                         "           <span class=\"pic-tag pic-tag-top\">" +
                         "               <span class=\"tag identificationDate\" title=\"" + orginUrl + "\" style=\"background-color: #00C0FF;\">" + picInfo.newName + "</span>" +