Bläddra i källkod

Merge branch 'master' of https://git.steerinfo.com/XTEMS/xt-ems-api

# Conflicts:
#	src/main/java/com/steerinfo/ftp/uploadfile/service/impl/UploadFileServiceImpl.java
lirl 3 år sedan
förälder
incheckning
5a273bf05f

+ 36 - 0
pom.xml

@@ -67,6 +67,42 @@
             <artifactId>poi-ooxml</artifactId>
             <version>3.17</version>
         </dependency>
+		<dependency>
+			<groupId>org.apache.poi</groupId>
+			<artifactId>poi</artifactId>
+			<version>3.17</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.poi</groupId>
+			<artifactId>poi-scratchpad</artifactId>
+			<version>3.17</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.poi</groupId>
+			<artifactId>poi-ooxml-schemas</artifactId>
+			<version>3.17</version>
+		</dependency>
+		<dependency>
+			<groupId>org.apache.poi</groupId>
+			<artifactId>ooxml-schemas</artifactId>
+			<version>1.3</version>
+		</dependency>
+		<dependency>
+			<groupId>fr.opensagres.xdocreport</groupId>
+			<artifactId>xdocreport</artifactId>
+			<version>2.0.1</version>
+		</dependency>
+<!--		被收购了,2.0.1版本开始向下兼容-->
+<!--		<dependency>-->
+<!--			<groupId>fr.opensagres.xdocreport</groupId>-->
+<!--			<artifactId>org.apache.poi.xwpf.converter.core</artifactId>-->
+<!--			<version>1.0.6</version>-->
+<!--		</dependency>-->
+<!--		<dependency>-->
+<!--			<groupId>fr.opensagres.xdocreport</groupId>-->
+<!--			<artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>-->
+<!--			<version>1.0.6</version>-->
+<!--		</dependency>-->
 	</dependencies>
 
 	<build>

+ 39 - 30
src/main/java/com/steerinfo/ftp/securitytype/controller/SecurityTypeController.java

@@ -14,8 +14,10 @@ import io.swagger.annotations.ApiOperation;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
-import java.util.*;
-import java.util.stream.Collectors;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
 
 /**
  * SecurityType RESTful接口:
@@ -57,29 +59,33 @@ public class SecurityTypeController extends BaseRESTfulController {
     //@RequiresPermissions("securitytype:view")
     @GetMapping(value = "/like/")
     public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize,String[] Info){
+        String securityInfo = parmas.get("securityInfo").toString().replace(",","|");
+        parmas.put("securityInfo",securityInfo);
         PageList<SecurityType> list = securityTypeService.queryLikeForPage(parmas, pageNum, pageSize);
         //在前端已经判断过权限,后端保险,后期服务器压力大可以注释
-        List<String> infoList = Arrays.asList(Info);
-        List<SecurityType> securityTypeList= new ArrayList<>();
-        Integer total = 0;
-        for (int i = 0;i < list.getList().size();i++){
-            SecurityType securityInfo = (SecurityType) list.getList().get(i);
-            if (securityInfo.getSecurityInfo() != null && !"".equals(securityInfo.getSecurityInfo())) {
-                List<String> infoList2= Arrays.asList(securityInfo.getSecurityInfo().split(",")
-                ).stream().map(s -> (s.trim())).collect(Collectors.toList());
-                infoList2.retainAll(infoList);
-                if (infoList2.size()>0){
-                    securityTypeList.add(securityInfo);
-                }else{
-                    total++;
-                }
-                continue;
-            }
-            securityTypeList.add(securityInfo);
-            continue;
-        }
-        list.setList(securityTypeList);
-        list.setTotal(list.getTotal()-total);
+        //List<String> infoList = Arrays.asList(Info);
+        //List<SecurityType> securityTypeList= new ArrayList<>();
+        //Integer total = 0;
+        //if(infoList.size()!=0){
+        //for (int i = 0;i < list.getList().size();i++){
+        //    SecurityType securityInfo = (SecurityType) list.getList().get(i);
+        //    if (securityInfo.getSecurityInfo() != null && !"".equals(securityInfo.getSecurityInfo())) {
+        //        List<String> infoList2= Arrays.asList(securityInfo.getSecurityInfo().split(",")
+        //        ).stream().map(s -> (s.trim())).collect(Collectors.toList());
+        //        infoList2.retainAll(infoList);
+        //        if (infoList2.size()>0){
+        //            securityTypeList.add(securityInfo);
+        //        }else{
+        //            total++;
+        //        }
+        //        continue;
+        //    }
+        //    securityTypeList.add(securityInfo);
+        //    continue;
+        //}
+        //list.setList(securityTypeList);
+        //list.setTotal(list.getTotal()-total);
+        //}
         return success(list);
     }
     
@@ -181,13 +187,14 @@ public class SecurityTypeController extends BaseRESTfulController {
     @GetMapping(value = "/gettree/")
     public RESTfulResult getTree(@RequestParam HashMap parameters){
         TreeUtils treeUtils = new TreeUtils();
-        String[] securityInfo =parameters.get("securityInfo").toString().split(",");
-        List<SecurityType> lists = securityTypeService.getTree();
-        for (int i = 0; i <securityInfo.length; i++) {
-        List<SecurityType> list = securityTypeService.getTreeByInfo(securityInfo[i]);
-        lists.removeAll(list);
-        lists.addAll(list);
-        }
+        String securityInfo = parameters.get("securityInfo").toString().replaceAll(",","|");
+        //String[] securityInfo =parameters.get("securityInfo").toString().split(",");
+        List<SecurityType> lists = securityTypeService.getTreeByInfo("("+securityInfo+")");
+        //for (int i = 0; i <securityInfo.length; i++) {
+        //List<SecurityType> list = securityTypeService.getTreeByInfo(securityInfo[i]);
+        //lists.removeAll(list);
+        //lists.addAll(list);
+        //}
         return success(treeUtils.getTreeData(lists));
     }
 
@@ -201,6 +208,8 @@ public class SecurityTypeController extends BaseRESTfulController {
             }
             parmas.put("id", id);
         }
+        String securityInfo = parmas.get("securityInfo").toString().replace(",","|");
+        parmas.put("securityInfo","("+securityInfo+")");
         List<SecurityType> idAndName = securityTypeService.getIdAndName(parmas);
         return  success(idAndName);
     }

+ 12 - 6
src/main/java/com/steerinfo/ftp/securitytype/mapper/SecurityTypeMapper.xml

@@ -82,7 +82,9 @@
         and SECURITY_NAME LIKE '%${securityName}%'
       </if>
       <if test="securityInfo != null and securityInfo != ''">
-        and SECURITY_INFO LIKE '%${securityInfo}%'
+        and SECURITY_INFO is null
+        OR SECURITY_INFO = ''
+        OR REGEXP_LIKE(SECURITY_INFO,'(${securityInfo})')
       </if>
       <if test="seqno != null">
         and SEQNO = #{seqno}
@@ -394,16 +396,18 @@
   <!-- 请将自己写的代码放在此标签之下,方便以后粘贴复制。-->
   <select id="getTree" resultMap="BaseResultMap">
     select ID, SECURITY_NAME, SECURITY_PARENTID, SECURITY_NODE from SECURITY_TYPE
-    WHERE 1=1 and SECURITY_INFO is null OR SECURITY_INFO = ''
+    WHERE 1=1 and SECURITY_INFO is null OR SECURITY_INFO = '' OR REGEXP_LIKE(SECURITY_TYPE,'(2|师傅|NULL|)')
     order by SEQNO
   </select>
 
   <select id="getTreeByInfo" parameterType="java.lang.String" resultMap="BaseResultMap">
     select ID, SECURITY_NAME, SECURITY_PARENTID, SECURITY_NODE from SECURITY_TYPE
     WHERE 1=1
-<!--      <if test="securityInfo != null and securityInfo != ''">-->
-      AND SECURITY_INFO like '%'||#{securityInfo}||'%'
-<!--      </if>-->
+    <if test="_parameter != null and _parameter != ''">
+      and SECURITY_INFO is null
+      OR SECURITY_INFO = ''
+      OR REGEXP_LIKE(SECURITY_INFO,#{securityInfo})
+    </if>
     order by SEQNO
   </select>
 
@@ -416,7 +420,9 @@
   <!--查询下拉框的值-->
   <select id="getIdAndName" parameterType="java.util.HashMap" resultMap="BaseResultMap">
     SELECT ID, SECURITY_NAME, SECURITY_NODE FROM SECURITY_TYPE
-    where 1=1
+    where 1=1 and SECURITY_INFO is null
+    OR SECURITY_INFO = ''
+    OR REGEXP_LIKE(SECURITY_INFO,#{securityInfo})
     ORDER BY SECURITY_NAME
   </select>
 

+ 61 - 21
src/main/java/com/steerinfo/ftp/uploadfile/controller/UploadFileController.java

@@ -7,7 +7,6 @@ import com.steerinfo.framework.service.pagehelper.PageList;
 import com.steerinfo.framework.utils.collection.ListUtils;
 import com.steerinfo.ftp.securitytype.mapper.SecurityTypeMapper;
 import com.steerinfo.ftp.securitytype.model.SecurityType;
-import com.steerinfo.ftp.securitytype.service.ISecurityTypeService;
 import com.steerinfo.ftp.uploadfile.model.UploadFile;
 import com.steerinfo.ftp.uploadfile.service.IUploadFileService;
 import com.steerinfo.ftp.uploadfile.utils.FtpFileUtil;
@@ -15,20 +14,15 @@ import com.steerinfo.ftp.uploadfile.utils.IDutils;
 import io.swagger.annotations.ApiImplicitParam;
 import io.swagger.annotations.ApiImplicitParams;
 import io.swagger.annotations.ApiOperation;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.ibatis.annotations.Param;
-import org.apache.shiro.authz.annotation.RequiresPermissions;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 
-import javax.servlet.http.HttpServletRequest;
-import java.io.File;
+import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
 import java.io.InputStream;
 import java.text.SimpleDateFormat;
 import java.util.*;
-import java.math.BigDecimal;
 
 /**
  * UploadFile RESTful接口:
@@ -59,7 +53,6 @@ public class UploadFileController extends BaseRESTfulController {
         @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
         @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
     })
-    //@RequiresPermissions("uploadfile:view")
     @GetMapping(value = "/")
     public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
         PageList<UploadFile> list = uploadFileService.queryForPage(parmas, pageNum, pageSize);
@@ -74,6 +67,8 @@ public class UploadFileController extends BaseRESTfulController {
     //@RequiresPermissions("uploadfile:view")
     @GetMapping(value = "/like/")
     public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
+        String fileType = parmas.get("fileType").toString().replace(",","|");
+        parmas.put("fileType",fileType);
         PageList<UploadFile> list = uploadFileService.queryLikeForPage(parmas, pageNum, pageSize);
         return success(list);
     }
@@ -111,14 +106,27 @@ public class UploadFileController extends BaseRESTfulController {
 
     @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
     @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
-    //@RequiresPermissions("uploadfile:delete")
-    @DeleteMapping(value = "/{id}")//String
-    public RESTfulResult delete(@PathVariable String id){
+    @DeleteMapping(value = "/{id}")
+    public RESTfulResult delete(@PathVariable String id) throws Exception {
     	List<String> list = Arrays.asList(id.split(","));
+    	String path = null;
+    	try {
     	if(ListUtils.isNotEmpty(list)) {
 	    	List<String> ids = ListUtils.convertList(list);
-			  uploadFileService.delete(ids);
+	    	for (String item : ids) {
+                UploadFile uploadFile = uploadFileService.getById(item);
+                path = uploadFile.getFileUrl();
+               if (ftpFileUtil.deleteFile(path)){
+                   uploadFileService.delete(item);
+               }else{
+                   return failed(null,"部分文件删除失败");
+               }
+            }
+            //uploadFileService.delete(ids);
     	}
+        } catch (Exception e) {
+    	    return failed(null,"删除失败");
+        }
       return success();
     }
     @PostMapping("/file")
@@ -136,29 +144,62 @@ public class UploadFileController extends BaseRESTfulController {
             String filePath = simpleDateFormat.format(new Date());
             InputStream inputStream = file.getInputStream();
              boolean result = ftpFileUtil.uploadToFtp(inputStream,securityType.getSecurityUploadUrl()+filePath,newName,false);
-            // boolean result = ftpFileUtil.uploadFile(filePath,newName,ftpFileUtil.getFTP_BASEPATH(),inputStream);
+            inputStream.close();
             if(result){
                 UploadFile uploadFile = new UploadFile();
                 uploadFile.setFileName(oldName);
-                uploadFile.setFileUrl(securityType.getSecurityUploadUrl()+filePath+newName);
+                uploadFile.setFileUrl(securityType.getSecurityUploadUrl()+filePath+"/"+newName);
+                uploadFile.setFileType(securityType.getSecurityType());
                 uploadFile.setUploadTime(new Date());
                 uploadFile.setCreateMan(userId);
                 uploadFile.setType(securityType.getId());
                 uploadFile.setCreateTime(new Date());
                 uploadFileService.add(uploadFile);
-            }else {
-                return  failed(null,"上传文件失败");
+                return success();
             }
         }catch (Exception e){
             e.getMessage();
         }
-           return success();
+        return  failed(null,"上传文件失败");
     }
 
+    /**
+     * 预览文件
+     * @param parmas
+     * @return
+     * @throws IOException
+     */
     @GetMapping("/getfile")
-    public InputStream downloadFile (@Param("filename") String filename)throws IOException {
-        InputStream inputStream = ftpFileUtil.downloadFile(filename);
-        return  inputStream;
+    public RESTfulResult downloadFile (@RequestParam HashMap parmas)throws IOException {
+        String fileName = parmas.get("fileName").toString();
+        String fileUrl = parmas.get("fileUrl").toString();
+        String str = fileName+"预览失败";
+        try {
+            str = ftpFileUtil.downloadFile(fileName,fileUrl);
+        } catch (Exception e){
+            e.printStackTrace();
+            return failed(null, "预览失败");
+        }
+        return success(str);
+    }
+
+    /**
+     * 下载文件
+     * @param path
+     * @param fileName
+     * @param response
+     */
+    @RequestMapping(value = "/downloadFile")
+    public void downloadFile(@RequestParam("fileUrl") String path, @RequestParam("fileName") String fileName, HttpServletResponse response) {
+        try {
+            boolean result = ftpFileUtil.download(response, fileName, path);
+            if (!result) {
+                //logger.error("下载文件<" + fileName + ">失败,文件不存在");
+                response.sendError(HttpServletResponse.SC_NOT_FOUND, "下载文件失败,文件目录不存在或文件不存在。");
+            }
+        } catch (Exception e) {
+            //logg.error("下载文件<" + fileName + ">失败", e);
+        }
     }
 
     @GetMapping("/getIdAndName")
@@ -166,5 +207,4 @@ public class UploadFileController extends BaseRESTfulController {
         Set<UploadFile> idAndName = uploadFileService.getIdAndName();
         return success(idAndName);
     }
-
 }

+ 4 - 3
src/main/java/com/steerinfo/ftp/uploadfile/mapper/UploadFileMapper.java

@@ -2,12 +2,13 @@ package com.steerinfo.ftp.uploadfile.mapper;
 
 import com.steerinfo.framework.mapper.IBaseMapper;
 import com.steerinfo.ftp.uploadfile.model.UploadFile;
-import java.math.*;
-import java.util.Set;
-
 import org.apache.ibatis.annotations.Mapper;
 
+import java.util.Set;
+
 @Mapper
 public interface UploadFileMapper extends IBaseMapper<UploadFile, String> {
     Set<UploadFile> getIdAndName ();
+
+    Set<UploadFile> getTag ();
 }

+ 23 - 5
src/main/java/com/steerinfo/ftp/uploadfile/mapper/UploadFileMapper.xml

@@ -6,6 +6,7 @@
     <result column="FILE_NAME" jdbcType="VARCHAR" property="fileName" />
     <result column="FILE_URL" jdbcType="VARCHAR" property="fileUrl" />
     <result column="TYPE" jdbcType="VARCHAR" property="type" />
+    <result column="FILE_TYPE" jdbcType="VARCHAR" property="fileType" />
     <result column="UPLOAD_TIME" jdbcType="TIMESTAMP" property="uploadTime" />
     <result column="CREATE_MAN" jdbcType="VARCHAR" property="createMan" />
     <result column="CREATE_TIME" jdbcType="TIMESTAMP" property="createTime" />
@@ -14,11 +15,11 @@
   </resultMap>
   <sql id="columns">
     ID, FILE_NAME, FILE_URL, TYPE, UPLOAD_TIME, CREATE_MAN, CREATE_TIME, UPDATE_MAN, 
-    UPDATE_TIME
+    UPDATE_TIME, FILE_TYPE
   </sql>
   <sql id="columns_alias">
     t.ID, t.FILE_NAME, t.FILE_URL, t.TYPE, t.UPLOAD_TIME, t.CREATE_MAN, t.CREATE_TIME, 
-    t.UPDATE_MAN, t.UPDATE_TIME
+    t.UPDATE_MAN, t.UPDATE_TIME, t.FILE_TYPE
   </sql>
   <sql id="select">
     SELECT <include refid="columns"/> FROM UPLOAD_FILE
@@ -55,6 +56,9 @@
       <if test="updateTime != null">
         and TO_CHAR(UPDATE_TIME,'yyyy-MM-dd') = #{updateTime}
       </if>
+      <if test="fileType != null and fileType != ''">
+        and FILE_TYPE = #{fileType}
+      </if>
     </where>
   </sql>
   <sql id="whereLike">
@@ -86,6 +90,11 @@
       <if test="updateTime != null">
         and TO_CHAR(UPDATE_TIME,'yyyy-MM-dd') = #{updateTime}
       </if>
+      <if test="fileType != null and fileType != ''">
+<!--        and FILE_TYPE is null-->
+<!--        OR FILE_TYPE = ''-->
+        AND REGEXP_LIKE(FILE_TYPE,'(${fileType})')
+      </if>
     </where>
   </sql>
   <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
@@ -123,11 +132,12 @@
   <insert id="insert" parameterType="com.steerinfo.ftp.uploadfile.model.UploadFile">
     insert into UPLOAD_FILE (ID, FILE_NAME, FILE_URL, 
       TYPE, UPLOAD_TIME, CREATE_MAN, 
-      CREATE_TIME, UPDATE_MAN, UPDATE_TIME
+      CREATE_TIME, UPDATE_MAN, UPDATE_TIME,FILE_TYPE
       )
     values (#{id,jdbcType=VARCHAR}, #{fileName,jdbcType=VARCHAR}, #{fileUrl,jdbcType=VARCHAR}, 
       #{type,jdbcType=VARCHAR}, #{uploadTime,jdbcType=TIMESTAMP}, #{createMan,jdbcType=VARCHAR}, 
-      #{createTime,jdbcType=TIMESTAMP}, #{updateMan,jdbcType=VARCHAR}, #{updateTime,jdbcType=TIMESTAMP}
+      #{createTime,jdbcType=TIMESTAMP}, #{updateMan,jdbcType=VARCHAR}, #{updateTime,jdbcType=TIMESTAMP},
+      #{fileType,jdbcType=VARCHAR}
       )
   </insert>
   <insert id="insertSelective" parameterType="com.steerinfo.ftp.uploadfile.model.UploadFile">
@@ -142,6 +152,9 @@
       <if test="fileUrl != null">
         FILE_URL,
       </if>
+      <if test="fileType != null">
+        FILE_TYPE,
+      </if>
       <if test="type != null">
         TYPE,
       </if>
@@ -171,6 +184,9 @@
       <if test="fileUrl != null">
         #{fileUrl,jdbcType=VARCHAR},
       </if>
+      <if test="fileType != null">
+        #{fileType,jdbcType=VARCHAR},
+      </if>
       <if test="type != null">
         #{type,jdbcType=VARCHAR},
       </if>
@@ -315,5 +331,7 @@
   <select id="getIdAndName" resultMap="BaseResultMap">
     select distinct  ID, FILE_NAME  FROM  UPLOAD_FILE
   </select>
-  
+  <select id="getTag" resultMap="BaseResultMap">
+    select distinct FILE_TYPE FROM UPLOAD_FILE
+  </select>
 </mapper>

+ 12 - 1
src/main/java/com/steerinfo/ftp/uploadfile/model/UploadFile.java

@@ -33,6 +33,12 @@ public class UploadFile implements IBasePO<String> {
     @ApiModelProperty(value="所属类别",required=false)
     private String type;
 
+    /**
+     * 所属类别(TYPE,VARCHAR,200)
+     */
+    @ApiModelProperty(value="文件分类",required=false)
+    private String fileType;
+
     /**
      * 上传时间(UPLOAD_TIME,TIMESTAMP,7)
      */
@@ -107,6 +113,10 @@ public class UploadFile implements IBasePO<String> {
         this.type = type == null ? null : type.trim();
     }
 
+    public String getFileType() { return fileType; }
+
+    public void setFileType(String fileType) { this.fileType = fileType == null ? null : fileType.trim(); }
+
     public Date getUploadTime() {
         return uploadTime;
     }
@@ -157,8 +167,9 @@ public class UploadFile implements IBasePO<String> {
         sb.append(", fileName=").append(fileName);
         sb.append(", fileUrl=").append(fileUrl);
         sb.append(", type=").append(type);
+        sb.append(", fileType=").append(fileType);
         sb.append(", uploadTime=").append(uploadTime);
-        sb.append(", createMan=").append(createMan);
+        sb.append(", createMam=").append(createMan);
         sb.append(", createTime=").append(createTime);
         sb.append(", updateMan=").append(updateMan);
         sb.append(", updateTime=").append(updateTime);

+ 3 - 2
src/main/java/com/steerinfo/ftp/uploadfile/service/IUploadFileService.java

@@ -2,8 +2,7 @@ package com.steerinfo.ftp.uploadfile.service;
 
 import com.steerinfo.framework.service.IBaseService;
 import com.steerinfo.ftp.uploadfile.model.UploadFile;
-import java.util.Date;
-import java.math.BigDecimal;
+
 import java.util.Set;
 
 /**
@@ -21,4 +20,6 @@ import java.util.Set;
  */
 public interface IUploadFileService extends IBaseService<UploadFile, String>{
     Set<UploadFile> getIdAndName ();
+
+    Set<UploadFile> getTag ();
 }

+ 324 - 103
src/main/java/com/steerinfo/ftp/uploadfile/utils/FtpFileUtil.java

@@ -1,98 +1,144 @@
 package com.steerinfo.ftp.uploadfile.utils;
 
-import org.apache.commons.net.ftp.FTP;
-import org.apache.commons.net.ftp.FTPClient;
-import org.apache.commons.net.ftp.FTPConnectionClosedException;
-import org.apache.commons.net.ftp.FTPReply;
+import com.steerinfo.framework.utils.io.IOUtils;
+import com.steerinfo.framework.utils.text.Charsets;
+import org.apache.commons.net.ftp.*;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 
-import java.io.*;
+import javax.servlet.http.HttpServletResponse;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Base64;
 
+/**
+ * POIExcelToHtml 文件转换:
+ *
+ * @author generator
+ * @version 1.0-SNAPSHOT 2021-08-09 18:06
+ * 类描述
+ * 修订历史:
+ * 日期:2021-08-09
+ * 作者:shadow
+ * 参考:
+ * 描述:
+ * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
+ * @see null
+ */
 @Component
 public class FtpFileUtil {
-    //ftp服务器ip地址
-    @Value("${custom.config.file-server.ip}") // 相关配置放在application.properties 中
+    /**
+     *   ftp服务器ip地址
+     *   相关配置放在application.properties 中
+     */
+    @Value("${custom.config.file-server.ip}")
      String FTP_ADDRESS;
-    //端口号
+
+    /**
+     *  端口号
+     */
     @Value("${custom.config.file-server.port}")
     Integer FTP_PORT;
-    //用户名
+    /**
+     * 用户名
+     */
     @Value("${custom.config.file-ftp-user}")
     String FTP_USERNAME;
-    //密码
+    /**
+     * 密码
+     */
     @Value("${custom.config.file-ftp-password}")
     String FTP_PASSWORD;
 
     private FTPClient ftpClient = new FTPClient();
-      //上传
-//    public boolean uploadFile(String filePath, String filename,String basePath, InputStream inputStream) {
-//        boolean result = false;
-//        try {
-//            // 连接FTP服务器
-//            ftpClient.setControlEncoding("UTF-8");
-//            ftpClient.enterLocalPassiveMode();
-//            ftpClient.connect(FTP_ADDRESS, FTP_PORT);
-//            ftpClient.login(FTP_USERNAME, FTP_PASSWORD);
-//            int reply;
-//            reply = ftpClient.getReplyCode();
-//            if (!FTPReply.isPositiveCompletion(reply)) {
-//                ftpClient.disconnect();
-//                return result;
-//            }
-//            //切换到上传目录
-//            boolean changed = ftpClient.changeWorkingDirectory( FTP_BASEPATH+ filePath);
-//            if (!changed) {
-//                //如果目录不存在创建目录
-//                String[] dirs = filePath.split("/");
-//                String tempPath = basePath;
-//                for (String dir : dirs) {
-//                    if (null == dir || "".equals(dir)){
-//                        continue;
-//                    }
-//                    tempPath += "/" + dir;
-//                        if (!ftpClient.makeDirectory(tempPath)) {
-//                            return result;
-//                        } else {
-//                            ftpClient.changeWorkingDirectory(tempPath);
-//                        }
-//                }
-//            }
-//            System.out.println("当前目录" + ftpClient.printWorkingDirectory());
-//            //设置为被动模式
-//            // ftp.enterLocalPassiveMode();
-//            ftpClient.setControlEncoding("UTF-8");
-//            //设置上传文件的类型为二进制类型
-//            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
-//            //上传文件
-//            if (!ftpClient.storeFile(new String(filename.getBytes("UTF-8"), "ISO-8859-1"), inputStream)) {
-//                System.out.println("上传文件失败");
-//                return result;
-//            }
-//            ftpClient.logout();
-//            result = true;
-//        } catch (IOException e) {
-//            e.printStackTrace();
-//        } finally {
-//            if (ftpClient.isConnected()) {
-//                try {
-//                    inputStream.close();
-//                    ftpClient.disconnect();
-//                } catch (IOException ioe) {
-//                    ioe.getMessage();
-//                }
-//            }
-//        }
-//        return result;
-//    }
-
-    //上传
+    private static final String SPOT = ".";
+
+    /**
+     * 上传文件
+     * @param filePath 文件路径
+     * @param filename 文件名称
+     * @param basePath 上级目录
+     * @param inputStream 文件输入流
+     * @return 是否成功
+     */
+    public boolean uploadFile(String filePath, String filename,String basePath, InputStream inputStream) {
+        boolean result = false;
+        try {
+            // 连接FTP服务器
+            ftpClient.enterLocalPassiveMode();
+            ftpClient.connect(FTP_ADDRESS, FTP_PORT);
+            ftpClient.login(FTP_USERNAME, FTP_PASSWORD);
+            int reply;
+            reply = ftpClient.getReplyCode();
+            if (!FTPReply.isPositiveCompletion(reply)) {
+                ftpClient.disconnect();
+                return false;
+            }
+            //切换到上传目录
+            boolean changed = ftpClient.changeWorkingDirectory(filePath);
+            if (!changed) {
+                //如果目录不存在创建目录
+                String[] dirs = filePath.split("/");
+                String tempPath = basePath;
+                for (String dir : dirs) {
+                    if (null == dir || "".equals(dir)){
+                        continue;
+                    }
+                    tempPath += "/" + dir;
+                        if (!ftpClient.makeDirectory(tempPath)) {
+                            return false;
+                        } else {
+                            ftpClient.changeWorkingDirectory(tempPath);
+                        }
+                }
+            }
+            System.out.println("当前目录" + ftpClient.printWorkingDirectory());
+            //设置为被动模式
+
+            //设置上传文件的类型为二进制类型
+            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
+            //上传文件
+            if (!ftpClient.storeFile(filename, inputStream)) {
+                System.out.println("上传文件失败");
+                return false;
+            }
+            ftpClient.logout();
+            result = true;
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            if (ftpClient.isConnected()) {
+                try {
+                    inputStream.close();
+                    ftpClient.disconnect();
+                } catch (IOException ioe) {
+                    ioe.printStackTrace();
+                }
+            }
+        }
+        return result;
+    }
+
+    /***
+     * 上传
+     * @param buffIn 文件流
+     * @param filePath 文件路径
+     * @param fileName 文件名称
+     * @param needDelete 是否删除
+     * @return 是否成功
+     * @throws FTPConnectionClosedException ftp错误
+     * @throws IOException io流错误
+     * @throws Exception 普通错误
+     */
     public boolean uploadToFtp(InputStream buffIn,String filePath, String fileName, boolean needDelete)
             throws FTPConnectionClosedException, IOException, Exception{
-        boolean result = false;
+        boolean result;
         try {
             //建立连接
             connectToServer();
+            ftpClient.changeWorkingDirectory("/");
             setFileType(FTP.BINARY_FILE_TYPE);
             int reply = ftpClient.getReplyCode();
             if (!FTPReply.isPositiveCompletion(reply)) {
@@ -100,13 +146,13 @@ public class FtpFileUtil {
                 throw new IOException("failed to connect to the FTP Server:" + FTP_ADDRESS);
             }
             //进入文件目录
-            boolean changeWork = ftpClient.changeWorkingDirectory( filePath);
+            boolean changeWork = ftpClient.changeWorkingDirectory(filePath);
             if(!changeWork){
                 if(!createDirectory(filePath)){
-                    return result;
+                    return false;
                 }
             }
-            result = ftpClient.storeFile(new String(fileName.getBytes("UTF-8"), "ISO-8859-1"),buffIn);
+            result = ftpClient.storeFile(fileName,buffIn);
             if(needDelete){
                 ftpClient.deleteFile(fileName);
             }
@@ -116,12 +162,10 @@ public class FtpFileUtil {
             } else {
                 System.out.println("uploadToFtp INFO: upload file  to ftp : failed!");
             }
-            buffIn.close();
         } catch (FTPConnectionClosedException e) {
             System.out.println("ftp连接被关闭!");
             throw e;
         }catch (Exception e){
-            result = false;
             System.out.println("ERR : upload file  to ftp : failed! ");
             throw  e;
         } finally {
@@ -139,10 +183,16 @@ public class FtpFileUtil {
         return  result;
     }
 
-    //下载
-    public InputStream downloadFile(String filename)
-            throws IOException {
-        InputStream inputStream = null;
+    /***
+     * 预览
+     * @param fileName 文件名
+     * @param filePath 文件路径
+     * @return 返回HTML
+     * @throws IOException io流错误
+     */
+    public String downloadFile(String fileName, String filePath) throws IOException {
+        InputStream inputStream;
+        String data = fileName + "预览失败";
         try {
             connectToServer();
             ftpClient.enterLocalPassiveMode();
@@ -153,31 +203,197 @@ public class FtpFileUtil {
                 ftpClient.disconnect();
                 throw new IOException("failed to connect to the FTP Server:" + FTP_ADDRESS);
             }
-            ftpClient.changeWorkingDirectory("/ems/file/2021/07/27");
-            File file =  new File("D:\\LRL"+File.separatorChar+filename);
-            OutputStream os = new FileOutputStream(file);
-            boolean b = ftpClient.retrieveFile(filename, os);
-            if(b == true){
-                os.close();
-                closeConnect();
+
+            String directory = filePath.substring(0,filePath.lastIndexOf("/")+1);
+            // 进入文件所在目录,注意编码格式,以能够正确识别中文目录
+            boolean cdStatus = ftpClient.changeWorkingDirectory(directory);
+            if (!cdStatus) {
+                return data;
+            }
+            String file = filePath.substring(filePath.lastIndexOf("/")+1);
+            // 检验文件是否存在
+            inputStream =ftpClient.retrieveFileStream(file);
+            String suffixName;
+            if(inputStream != null){
+                if (fileName != null && fileName.contains(SPOT)) {
+                    POIWordToHtml poiWordToHtml = new POIWordToHtml();
+                    suffixName = fileName.substring(fileName.indexOf(".")+1);
+                    switch (suffixName) {
+                        case "docx": data = poiWordToHtml.docxToHtml(inputStream);break;
+                        case "doc" : data = poiWordToHtml.docToHtml(inputStream); break;
+                        case "xlsx":
+                        case "xls" :
+                            data = POIExcelToHtml.excelToHtml(inputStream);break;
+                        case "pptx":
+                        case "ppt" :
+                            data = POIPptToHtml.pptToHtml(inputStream,suffixName);break;
+                        case "jpg" :
+                        case "gif" :
+                        case "png" :
+                        case "jpeg":
+                        case "jpe" :
+                            ByteArrayOutputStream stream = new ByteArrayOutputStream();
+                            IOUtils.copy(inputStream,stream);
+                            String imgStr = Base64.getEncoder().encodeToString(stream.toByteArray());
+                            data = "<img src=" + "\"data:image/"+suffixName+";base64," + imgStr + "\"" + "/>";
+                            stream.close();break;
+                        case "txt" :
+                            ByteArrayOutputStream txtStream = new ByteArrayOutputStream();
+                            IOUtils.copy(inputStream,txtStream);
+                            data = txtStream.toString();break;
+                        default : data = fileName + "文件暂时不支持预览。"; break;
+                    }
+                }
+                inputStream.close();
+                ftpClient.completePendingCommand();
             }
         } catch (FTPConnectionClosedException e){
             System.out.println("ftp连接被关闭!");
             throw e;
         } catch (Exception e) {
-            System.out.println("ERR : upload file " + filename + " from ftp : failed!");
+            System.out.println("ERR : upload file " + fileName + " from ftp : failed!"+e.getMessage());
+        } finally {
+            if(ftpClient.isConnected()){
+                closeConnect();
+            }
+        }
+        return data;
+    }
+
+    /**
+     * 下载
+     * @param response 响应头
+     * @param fileName 文件名
+     * @param filePath 文件路径
+     * @return 返回下载是否成功
+     */
+    public boolean download(HttpServletResponse response, String fileName, String filePath) {
+        boolean flag = false;
+        try{
+            connectToServer();
+            ftpClient.enterLocalPassiveMode();
+            // 设置传输二进制文件
+            setFileType(FTP.BINARY_FILE_TYPE);
+            int reply = ftpClient.getReplyCode();
+            if(!FTPReply.isPositiveCompletion(reply)){
+                ftpClient.disconnect();
+                throw new IOException("failed to connect to the FTP Server:" + FTP_ADDRESS);
+            }
+            String transferName = new String(fileName.getBytes(Charsets.UTF_8),Charsets.ISO_8859_1);
+            String directory = filePath.substring(0,filePath.lastIndexOf("/")+1);
+            String file = filePath.substring(filePath.lastIndexOf("/")+1);
+            // 进入文件所在目录,注意编码格式,以能够正确识别中文目录
+            ftpClient.changeWorkingDirectory(directory);
+            response.setCharacterEncoding("UTF-8");
+            response.setContentType("multipart/form-data;charset=UTF-8");
+            response.setHeader("Content-Disposition", "attachment; filename=\"" + transferName + "\"");
+            FTPFile[] fs = ftpClient.listFiles();
+            for (FTPFile ff : fs) {
+                if (ff.getName().equals(file)) {
+                    OutputStream os = response.getOutputStream();
+                    flag = ftpClient.retrieveFile(ff.getName(), os);
+                    os.flush();
+                    os.close();
+                    break;
+                }
+            }
+            closeConnect();
+
+        }catch (FTPConnectionClosedException ignored){
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        return flag;
+    }
+
+    /**
+     * 下载返回流
+     * @param fileName 文件名称
+     * @param filePath 文件路径
+     * @return 返回是否成功
+     */
+    public ByteArrayOutputStream download(String fileName, String filePath) {
+        ByteArrayOutputStream os = new ByteArrayOutputStream();
+        try{
+            connectToServer();
+            ftpClient.enterLocalPassiveMode();
+            // 设置传输二进制文件
+            setFileType(FTP.BINARY_FILE_TYPE);
+            int reply = ftpClient.getReplyCode();
+            if(!FTPReply.isPositiveCompletion(reply)){
+                ftpClient.disconnect();
+                throw new IOException("failed to connect to the FTP Server:" + FTP_ADDRESS);
+            }
+            String directory = filePath.substring(0,filePath.lastIndexOf("/")+1);
+            String file = filePath.substring(filePath.lastIndexOf("/")+1);
+            // 进入文件所在目录,注意编码格式,以能够正确识别中文目录
+            ftpClient.changeWorkingDirectory(directory);
+            FTPFile[] fs = ftpClient.listFiles();
+            for (FTPFile ff : fs) {
+                if (ff.getName().equals(file)) {
+                    os.close();
+                    break;
+                }
+            }
+            closeConnect();
+
+        }catch (FTPConnectionClosedException ignored){
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        return os;
+    }
+
+    public boolean deleteFile(String filePath) throws Exception {
+        boolean result;
+        try {
+            //建立连接
+            connectToServer();
+            ftpClient.changeWorkingDirectory("/");
+            setFileType(FTP.BINARY_FILE_TYPE);
+            int reply = ftpClient.getReplyCode();
+            if (!FTPReply.isPositiveCompletion(reply)) {
+                ftpClient.disconnect();
+                throw new IOException("failed to connect to the FTP Server:" + FTP_ADDRESS);
+            }
+            String directory = filePath.substring(0,filePath.lastIndexOf("/")+1);
+            String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
+            //进入文件目录
+            boolean changeWork = ftpClient.changeWorkingDirectory(directory);
+            if(!changeWork){
+                return false;
+            }
+             result = ftpClient.deleteFile(fileName);
+        } catch (FTPConnectionClosedException e) {
+            System.out.println("ftp连接被关闭!");
+            throw e;
+        }catch (Exception e){
+            System.out.println("ERR : delete file  to ftp : failed! ");
+            throw  e;
+        } finally {
+            if(ftpClient.isConnected()){
+                closeConnect();
+            }
         }
-        return inputStream;
+        return result;
     }
 
-    //建立连接
+    /***
+     * 建立连接
+     * @throws FTPConnectionClosedException ftp错误
+     * @throws Exception 普通错误
+     */
     private void connectToServer() throws FTPConnectionClosedException, Exception {
          if(!ftpClient.isConnected()){
              int reply;
              try {
                 //建立连接
                  ftpClient = new FTPClient();
-                 ftpClient.setControlEncoding("UTF-8");
+                 ftpClient.setControlEncoding("GBK");
                  ftpClient.enterLocalPassiveMode();
                  ftpClient.connect(FTP_ADDRESS, FTP_PORT);
                  ftpClient.login(FTP_USERNAME, FTP_PASSWORD);
@@ -196,7 +412,10 @@ public class FtpFileUtil {
          }
     }
 
-    //设置传输文件类型
+    /**
+     * 设置传输文件类型
+     * @param fileType 文件类型
+     */
     private void setFileType(int fileType) {
         try {
             ftpClient.setFileType(fileType);
@@ -206,7 +425,9 @@ public class FtpFileUtil {
         }
     }
 
-    //关闭连接
+    /**
+     *  关闭连接
+     */
     public void closeConnect() {
         try {
             if (ftpClient != null) {
@@ -218,10 +439,12 @@ public class FtpFileUtil {
         }
     }
 
-   //创建文件夹
-   public boolean createDirectory(String directory) throws IOException {
-       boolean isSuccess = false;
+    /**
+     * 创建文件夹
+     */
+   public boolean createDirectory(String directory) {
        try {
+           ftpClient.changeWorkingDirectory("/");
                String[] dirs = directory.split("/");
                String tempPath = "";
                for (String dir : dirs) {
@@ -230,7 +453,9 @@ public class FtpFileUtil {
                    }
                    tempPath += "/" + dir;
                    if (!ftpClient.makeDirectory(tempPath)) {
-                       return isSuccess;
+                       if(!ftpClient.changeWorkingDirectory(tempPath)){
+                           return false;
+                       }
                    } else {
                        ftpClient.changeWorkingDirectory(tempPath);
                    }
@@ -240,8 +465,4 @@ public class FtpFileUtil {
        }
            return true;
    }
-    //获取类型地址
-//    public String getFtpaddress (String type) {
-//        if(){}
-//    }
 }

+ 424 - 0
src/main/java/com/steerinfo/ftp/uploadfile/utils/POIExcelToHtml.java

@@ -0,0 +1,424 @@
+package com.steerinfo.ftp.uploadfile.utils;
+
+import org.apache.poi.hssf.usermodel.*;
+import org.apache.poi.hssf.util.HSSFColor;
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.xssf.usermodel.XSSFCellStyle;
+import org.apache.poi.xssf.usermodel.XSSFColor;
+import org.apache.poi.xssf.usermodel.XSSFFont;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * POIExcelToHtml 文件转换:
+ * @author generator
+ * @version 1.0-SNAPSHORT 2021-08-09 18:06
+ * 类描述
+ * 修订历史:
+ * 日期:2021-08-09
+ * 作者:shadow
+ * 参考:
+ * 描述:Execl转HTML
+ * @see null
+ * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
+ */
+public class POIExcelToHtml {
+
+	public static String excelToHtml(InputStream is) {
+
+		String htmlExcel = "预览文件失败";
+		try {
+			Workbook wb = WorkbookFactory.create(is);
+			if (wb instanceof XSSFWorkbook) {
+				XSSFWorkbook xWb = (XSSFWorkbook) wb;
+				htmlExcel = POIExcelToHtml.getExcelInfo(xWb);
+			} else if (wb instanceof HSSFWorkbook) {
+				HSSFWorkbook hWb = (HSSFWorkbook) wb;
+				htmlExcel = POIExcelToHtml.getExcelInfo(hWb);
+			}
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				is.close();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return htmlExcel;
+	}
+
+	private static String getExcelInfo(Workbook wb) {
+		StringBuffer sb = new StringBuffer();
+		int sheetCounts = wb.getNumberOfSheets();
+		// sb.append("<!DOCTYPE html> <html> <head> <meta charset='utf-8'
+		// /><title>HTML实例</title></head> ");
+
+		for (int i = 0; i < sheetCounts; i++) {
+			Sheet sheet = wb.getSheetAt(i);// 获取第一个Sheet的内容
+			int lastRowNum = sheet.getLastRowNum();
+			Map<String, String> map[] = getRowSpanColSpanMap(sheet);
+			// sb.append("<br><br>");
+			sb.append(sheet.getSheetName());
+			sb.append("<table style='border-collapse:collapse;' width='100%'>");
+			Row row = null; // 兼容
+			Cell cell = null; // 兼容
+			for (int rowNum = sheet.getFirstRowNum(); rowNum <= lastRowNum; rowNum++) {
+				row = sheet.getRow(rowNum);
+				if (row == null) {
+					sb.append("<tr><td > &nbsp;</td></tr>");
+					continue;
+				}
+				sb.append("<tr>");
+				int lastColNum = row.getLastCellNum();
+				for (int colNum = 0; colNum < lastColNum; colNum++) {
+					cell = row.getCell(colNum);
+					if (cell == null) { // 特殊情况 空白的单元格会返回null
+						sb.append("<td>&nbsp;</td>");
+						continue;
+					}
+
+					String stringValue = getCellValue(cell);//````````````
+					if (map[0].containsKey(rowNum + "," + colNum)) {
+						String pointString = map[0].get(rowNum + "," + colNum);
+						map[0].remove(rowNum + "," + colNum);
+						int bottomeRow = Integer.valueOf(pointString.split(",")[0]);
+						int bottomeCol = Integer.valueOf(pointString.split(",")[1]);
+						int rowSpan = bottomeRow - rowNum + 1;
+						int colSpan = bottomeCol - colNum + 1;
+						sb.append("<td rowspan= '" + rowSpan + "' colspan= '" + colSpan + "' ");
+					} else if (map[1].containsKey(rowNum + "," + colNum)) {
+						map[1].remove(rowNum + "," + colNum);
+						continue;
+					} else {
+						sb.append("<td ");
+					}
+
+					dealExcelStyle(wb, sheet, cell, sb);// 处理单元格样式
+					sb.append(">");
+					if (stringValue == null || "".equals(stringValue.trim())) {
+						sb.append(" &nbsp; ");
+					} else {
+						// 将ascii码为160的空格转换为html下的空格(&nbsp;)
+						sb.append(stringValue.replace(String.valueOf((char) 160), "&nbsp;"));
+					}
+					sb.append("</td>");
+				}
+				sb.append("</tr>");
+			}
+			sb.append("</table>");
+		}
+
+		// sb.append("</body></html> ");
+		return sb.toString();
+	}
+
+	private static Map<String, String>[] getRowSpanColSpanMap(Sheet sheet) {
+		Map<String, String> map0 = new HashMap<String, String>();
+		Map<String, String> map1 = new HashMap<String, String>();
+		int mergedNum = sheet.getNumMergedRegions();
+		CellRangeAddress range = null;
+		for (int i = 0; i < mergedNum; i++) {
+			range = sheet.getMergedRegion(i);
+			int topRow = range.getFirstRow();
+			int topCol = range.getFirstColumn();
+			int bottomRow = range.getLastRow();
+			int bottomCol = range.getLastColumn();
+			map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol);
+			// System.out.println(topRow + "," + topCol + "," + bottomRow + ","
+			// + bottomCol);
+			int tempRow = topRow;
+			while (tempRow <= bottomRow) {
+				int tempCol = topCol;
+				while (tempCol <= bottomCol) {
+					map1.put(tempRow + "," + tempCol, "");
+					tempCol++;
+				}
+				tempRow++;
+			}
+			map1.remove(topRow + "," + topCol);
+		}
+		Map[] map = { map0, map1 };
+		return map;
+	}
+
+	/**
+	 * 200 * 获取表格单元格Cell内容 201 * @param cell 202 * @return 203
+	 */
+	private static String getCellValue(Cell cell) {
+		String result = new String();
+		switch (cell.getCellType()) {
+			case Cell.CELL_TYPE_NUMERIC:// 数字类型
+				if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
+					SimpleDateFormat sdf = null;
+					if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("hh:mm")) {
+						sdf = new SimpleDateFormat("HH:mm");
+					} else if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
+							.getBuiltinFormat("yyyy-MM-dd HH:mm:ss")) {// 日期
+						sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+					} else {
+						sdf = new SimpleDateFormat("yyyy-MM-dd");
+					}
+					Date date = cell.getDateCellValue();
+					result = sdf.format(date);
+				} else if (cell.getCellStyle().getDataFormat() == 58) {
+					// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
+					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+					double value = cell.getNumericCellValue();
+					Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
+					result = sdf.format(date);
+				} else {
+					double value = cell.getNumericCellValue();
+					CellStyle style = cell.getCellStyle();
+					DecimalFormat format = new DecimalFormat();
+					String temp = style.getDataFormatString();
+					// 单元格设置成常规
+					if (temp.equals("General")) {
+						format.applyPattern("#");
+					}
+					result = format.format(value);
+				}
+				break;
+			case Cell.CELL_TYPE_STRING:// String类型
+				result = cell.getRichStringCellValue().toString();
+				break;
+			case Cell.CELL_TYPE_BLANK:
+				result = "";
+				break;
+			default:
+				result = "";
+				break;
+		}
+		return result;
+	}
+
+	/**
+	 * 251 * 处理表格样式 252 * @param wb 253 * @param sheet 254 * @param cell 255
+	 * * @param sb 256
+	 */
+	private static void dealExcelStyle(Workbook wb, Sheet sheet, Cell cell, StringBuffer sb) {
+
+		CellStyle cellStyle = cell.getCellStyle();
+		if (cellStyle != null) {
+			//short alignment = cellStyle.getAlignment();旧写法获取枚举数字;新写法获取枚举
+
+			sb.append("align='" + convertAlignToHtml(cellStyle.getAlignmentEnum()) + "' ");// 单元格内容的水平对齐方式
+			//short verticalAlignment = cellStyle.getVerticalAlignment();
+			//short verticalAlignment = cellStyle.getVerticalAlignmentEnum().getCode();
+			sb.append("valign='" + convertVerticalAlignToHtml(cellStyle.getVerticalAlignmentEnum()) + "' ");// 单元格中内容的垂直排列方式
+
+			if (wb instanceof XSSFWorkbook) {
+				XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont();
+				Boolean boldWeight = xf.getBold();
+				//short boldWeight = xf.getBoldweight();
+				String fontfamily = xf.getFontName();
+				int underline = xf.getUnderline();
+				boolean Italic = xf.getItalic();
+
+				sb.append("style='");
+				if (underline >= 1) {
+					sb.append("text-decoration:underline;"); // 字体型号
+				}
+				if (Italic) {
+					sb.append("font-style: italic;"); // 字体型号
+				}
+				sb.append("font-family:" + fontfamily + ";"); // 字体型号
+				sb.append("font-weight:" + (boldWeight ? "bold" : "100") + ";"); // 字体加粗
+				sb.append("font-size: " + xf.getFontHeight() / 2 + "%;"); // 字体大小
+				int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
+				sb.append("width:" + columnWidth + "px;");
+
+				XSSFColor xc = xf.getXSSFColor();
+				if (xc != null && !"".equals(xc)) {
+					sb.append("color:#" + xc.getARGBHex().substring(2) + ";"); // 字体颜色
+				}
+
+				XSSFColor bgColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
+				if (bgColor != null && !"".equals(bgColor)) {
+					sb.append("background-color:#" + bgColor.getARGBHex().substring(2) + ";"); // 背景颜色
+				}
+				sb.append(getBorderStyle(0, cellStyle.getBorderTop(),
+						((XSSFCellStyle) cellStyle).getTopBorderXSSFColor()));
+				sb.append(getBorderStyle(1, cellStyle.getBorderRight(),
+						((XSSFCellStyle) cellStyle).getRightBorderXSSFColor()));
+				sb.append(getBorderStyle(2, cellStyle.getBorderBottom(),
+						((XSSFCellStyle) cellStyle).getBottomBorderXSSFColor()));
+				sb.append(getBorderStyle(3, cellStyle.getBorderLeft(),
+						((XSSFCellStyle) cellStyle).getLeftBorderXSSFColor()));
+
+			} else if (wb instanceof HSSFWorkbook) {
+
+				HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb);
+				short fontColor = hf.getColor();
+				Boolean boldWeight = hf.getBold();
+				//short boldWeight = hf.getBoldweight();
+				String fontfamily = hf.getFontName();
+				int underline = hf.getUnderline();
+				boolean Italic = hf.getItalic();
+
+				sb.append("style='");
+				if (underline >= 1) {
+					// 字体型号
+					sb.append("text-decoration:underline;");
+				}
+				if (Italic) {
+					// 字体型号
+					sb.append("font-style: italic;");
+				}
+				// 类HSSFPalette用于求的颜色的国际标准形式
+				HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette();
+				HSSFColor hc = palette.getColor(fontColor);
+				// 字体加粗
+				sb.append("font-weight:" + (boldWeight ? "bold" : "100") + ";");
+				// 字体型号
+				sb.append("font-family:" + fontfamily + ";");
+				// 字体大小
+				sb.append("font-size: " + hf.getFontHeight() / 2 + "%;");
+				String fontColorStr = convertToStardColor(hc);
+				// 字体颜色
+				if (fontColorStr != null && !"".equals(fontColorStr.trim())) {
+					sb.append("color:" + fontColorStr + ";");
+				}
+				int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
+				sb.append("width:" + columnWidth + "px;");
+				short bgColor = cellStyle.getFillForegroundColor();
+				//short bgColor = cellStyle.getFillBackgroundColor();
+				hc = palette.getColor(bgColor);
+				String bgColorStr = convertToStardColor(hc);
+				if (bgColorStr != null && !"".equals(bgColorStr.trim())) {
+					// 背景颜色
+					sb.append("background-color:" + bgColorStr + ";");
+				}
+				/**
+				 * 旧版本 cellStyle.getBorderTop()
+				 * 新版本 cellStyle.getBorderTopEnum()
+				 */
+				sb.append(getBorderStyle(palette, 0, cellStyle.getBorderTop(), cellStyle.getTopBorderColor()));
+				sb.append(getBorderStyle(palette, 1, cellStyle.getBorderRight(), cellStyle.getRightBorderColor()));
+				sb.append(getBorderStyle(palette, 3, cellStyle.getBorderLeft(), cellStyle.getLeftBorderColor()));
+				sb.append(getBorderStyle(palette, 2, cellStyle.getBorderBottom(), cellStyle.getBottomBorderColor()));
+			}
+
+			sb.append("' ");
+		}
+	}
+
+	/**
+	 * 330 * 单元格内容的水平对齐方式 331 * @param alignment 332 * @return 333
+	 * @param alignment
+	 */
+	private static String convertAlignToHtml( HorizontalAlignment alignment) {
+
+		String align = "left";
+		/**
+		 * CellStyle.ALIGN_CENTER:旧写法
+		 * HorizontalAlignment.LEFT:新写法
+		 */
+		switch (alignment) {
+			case LEFT:
+				align = "left";
+				break;
+			case CENTER:
+				align = "center";
+				break;
+			case RIGHT:
+				align = "right";
+				break;
+			default:
+				break;
+		}
+		return align;
+	}
+
+	/**
+	 * 354 * 单元格中内容的垂直排列方式 355 * @param verticalAlignment 356 * @return 357
+	 * @param verticalAlignment
+	 */
+	private static String convertVerticalAlignToHtml(VerticalAlignment verticalAlignment) {
+
+		/**
+		 * 旧写法CellStyle.VERTICAL_BOTTOM:
+		 * 新写法VerticalAlignment.BOTTOM:
+		 */
+		String valign = "middle";
+		switch (verticalAlignment) {
+			case BOTTOM:
+				valign = "bottom";
+				break;
+			case CENTER:
+				valign = "center";
+				break;
+			case TOP:
+				valign = "top";
+				break;
+			default:
+				break;
+		}
+		return valign;
+	}
+
+	private static String convertToStardColor(HSSFColor hc) {
+
+		/**
+		 * 颜色定义变化
+		 * 旧版本 : HSSFColor.BLACK.index
+		 * 新版本 : IndexedColors.BLACK.index
+		 */
+		StringBuffer sb = new StringBuffer("");
+		if (hc != null) {
+			if (IndexedColors.AUTOMATIC.index == hc.getIndex()) {
+				return null;
+			}
+			sb.append("#");
+			for (int i = 0; i < hc.getTriplet().length; i++) {
+				sb.append(fillWithZero(Integer.toHexString(hc.getTriplet()[i])));
+			}
+		}
+
+		return sb.toString();
+	}
+
+	private static String fillWithZero(String str) {
+		if (str != null && str.length() < 2) {
+			return "0" + str;
+		}
+		return str;
+	}
+
+	static String[] bordesr = { "border-top:", "border-right:", "border-bottom:", "border-left:" };
+	static String[] borderStyles = { "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ",
+			"solid ", "solid", "solid", "solid", "solid", "solid" };
+
+	private static String getBorderStyle(HSSFPalette palette, int b, short s, short t) {
+		if (s == 0) {
+			return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
+		}
+		String borderColorStr = convertToStardColor(palette.getColor(t));
+		borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000" : borderColorStr;
+		return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
+
+	}
+
+	private static String getBorderStyle(int b, short s, XSSFColor xc) {
+		if (s == 0) {
+			return bordesr[b] + borderStyles[s] + "#d0d7e5 1px;";
+		}
+		if (xc != null && !"".equals(xc)) {
+			// t.getARGBHex();
+			String borderColorStr = xc.getARGBHex();
+			borderColorStr = borderColorStr == null || borderColorStr.length() < 1 ? "#000000"
+					: borderColorStr.substring(2);
+			return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
+		}
+		return "";
+	}
+
+}

+ 155 - 0
src/main/java/com/steerinfo/ftp/uploadfile/utils/POIPptToHtml.java

@@ -0,0 +1,155 @@
+package com.steerinfo.ftp.uploadfile.utils;
+
+import org.apache.poi.hslf.usermodel.*;
+import org.apache.poi.xslf.usermodel.*;
+
+import javax.imageio.ImageIO;
+import java.awt.*;
+import java.awt.geom.Rectangle2D;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Base64;
+
+/**
+ *
+ * @author ruand http://blog.csdn.net/emoven/article/details/52683215
+ */
+public class POIPptToHtml {
+
+	private final static String PPT = "ppt";
+	private final static String PPTX = "pptx";
+
+	public static String pptToHtml(InputStream is, String type) {
+		String htmlStr = "预览失败";
+		try {
+				if (PPT.equals(type)) {
+					 htmlStr = toImage2003(is);
+				} else if (PPTX.equals(type)) {
+					 htmlStr = toImage2007(is);
+				} else {
+					htmlStr = "the file is not a ppt";
+				}
+
+			} catch (Exception e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+		return htmlStr;
+	}
+
+	public static String toImage2007(InputStream is) throws Exception {
+		String htmlStr = "预览失败";
+		XMLSlideShow ppt = new XMLSlideShow(is);
+		is.close();
+		Dimension pgsize = ppt.getPageSize();
+		System.out.println(pgsize.width + "--" + pgsize.height);
+
+		StringBuffer sb = new StringBuffer();
+		for (int i = 0; i < ppt.getSlides().size(); i++) {
+			try {
+				// 防止中文乱码
+				for (XSLFShape shape : ppt.getSlides().get(i).getShapes()) {
+					if (shape instanceof XSLFTextShape) {
+						XSLFTextShape tsh = (XSLFTextShape) shape;
+						for (XSLFTextParagraph p : tsh) {
+							for (XSLFTextRun r : p) {
+								r.setFontFamily("宋体");
+							}
+						}
+					}
+				}
+				BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
+				Graphics2D graphics = img.createGraphics();
+				// clear the drawing area
+				graphics.setPaint(Color.white);
+				graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
+				// render
+				ppt.getSlides().get(i).draw(graphics);
+				ByteArrayOutputStream stream = new ByteArrayOutputStream();
+				javax.imageio.ImageIO.write(img, "png", stream);
+				String imgStr = Base64.getEncoder().encodeToString(stream.toByteArray());
+				// save the output
+				sb.append("<br>");
+				sb.append("<img src=" + "\"data:image/png;base64," + imgStr + "\"" + "/>");
+				stream.close();
+			} catch (Exception e) {
+				System.out.println("第" + i + "张ppt转换出错");
+			}
+		}
+		System.out.println("success");
+		htmlStr = sb.toString();
+
+		return htmlStr;
+	}
+
+	public static String toImage2003(InputStream is) {
+		String htmlStr = "预览失败";
+		try {
+			HSLFSlideShow ppt = new HSLFSlideShow(is);
+			Dimension pgsize = ppt.getPageSize();
+			StringBuffer sb = new StringBuffer();
+			for (int i = 0; i < ppt.getSlides().size(); i++) {
+				// 防止中文乱码
+				for (HSLFShape shape : ppt.getSlides().get(i).getShapes()) {
+					if (shape instanceof HSLFTextShape) {
+						HSLFTextShape tsh = (HSLFTextShape) shape;
+						for (HSLFTextParagraph p : tsh) {
+							for (HSLFTextRun r : p) {
+								r.setFontFamily("宋体");
+							}
+						}
+					}
+				}
+				BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
+				Graphics2D graphics = img.createGraphics();
+				// clear the drawing area
+				graphics.setPaint(Color.white);
+				graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
+				// render
+				ppt.getSlides().get(i).draw(graphics);
+				ByteArrayOutputStream stream = new ByteArrayOutputStream();
+				//String imageDir = targetDir + "/" + pptFileName + "/";
+				//FileUtils.createDir(imageDir);// create image dir
+				//String imagePath = imageDir + pptFileName + "-" + (i + 1) + ".png";
+				javax.imageio.ImageIO.write(img, "png", stream);
+				String imgStr = Base64.getEncoder().encodeToString(stream.toByteArray());
+				sb.append("<br>");
+				sb.append("<img src=" + "\"data:image/png;base64," + imgStr + "\"" + "/>");
+				stream.close();
+
+			}
+			System.out.println("success");
+			htmlStr = sb.toString();
+		} catch (Exception e) {
+
+		}
+		return htmlStr;
+	}
+
+	/***
+	 * 功能 :调整图片大小
+	 *
+	 * @param srcImgPath
+	 *            原图片路径
+	 * @param distImgPath
+	 *            转换大小后图片路径
+	 * @param width
+	 *            转换后图片宽度
+	 * @param height
+	 *            转换后图片高度
+	 */
+	public static void resizeImage(String srcImgPath, String distImgPath, int width, int height) throws IOException {
+
+		File srcFile = new File(srcImgPath);
+		Image srcImg = ImageIO.read(srcFile);
+		BufferedImage buffImg = null;
+		buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+		buffImg.getGraphics().drawImage(srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
+
+		ImageIO.write(buffImg, "JPEG", new File(distImgPath));
+
+	}
+}

+ 135 - 0
src/main/java/com/steerinfo/ftp/uploadfile/utils/POIWordToHtml.java

@@ -0,0 +1,135 @@
+package com.steerinfo.ftp.uploadfile.utils;
+
+import fr.opensagres.poi.xwpf.converter.xhtml.Base64EmbedImgManager;
+import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
+import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
+import org.apache.poi.hwpf.HWPFDocumentCore;
+import org.apache.poi.hwpf.converter.WordToHtmlConverter;
+import org.apache.poi.hwpf.converter.WordToHtmlUtils;
+import org.apache.poi.hwpf.usermodel.Picture;
+import org.apache.poi.xwpf.usermodel.XWPFDocument;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Base64;
+
+/**
+ * POIExcelToHtml 文件转换:
+ *
+ * @author generator
+ * @version 1.0-SNAPSHORT 2021-08-09 18:06
+ * 类描述
+ * 修订历史:
+ * 日期:2021-08-09
+ * 作者:shadow
+ * 参考:https://blog.csdn.net/u013585096/article/details/85104888
+ * 描述:Execl转HTML
+ * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
+ * @see null
+ */
+public class POIWordToHtml {
+    private static final String ENCODING = "GB2312";// UTF-8
+
+
+    public String docToHtml(InputStream input) throws Exception {
+        String htmlData = "预览失败";
+        try {
+        HWPFDocumentCore wordDocument = WordToHtmlUtils.loadDoc(input);
+        WordToHtmlConverter wordToHtmlConverter = new ImageConverter(
+                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
+        );
+        //wordToHtmlConverter.setPicturesManager(new PicturesManager() {
+        //    @Override
+        //    public String savePicture(byte[] content,
+        //                              PictureType pictureType, String suggestedName,
+        //                              float widthInches, float heightInches) {
+        //            //给生成的页面写图片的路径
+        //            return "word/media/" + suggestedName;
+        //    }
+        //});
+        wordToHtmlConverter.processDocument(wordDocument);
+        Document htmlDocument = wordToHtmlConverter.getDocument();
+        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
+        DOMSource domSource = new DOMSource(htmlDocument);
+        StreamResult streamResult = new StreamResult(outStream);
+        TransformerFactory tf = TransformerFactory.newInstance();
+        Transformer serializer = tf.newTransformer();
+        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
+        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
+        serializer.setOutputProperty(OutputKeys.METHOD, "html");
+        serializer.transform(domSource, streamResult);
+        htmlData =  outStream.toString();
+        outStream.close();
+        } catch (Exception e){
+            e.printStackTrace();
+        }
+        return htmlData;
+    }
+
+    public String docxToHtml(InputStream inputStream) throws IOException {
+        String htmlData = "预览失败";
+        try{
+        XWPFDocument docxDocument = new XWPFDocument(inputStream);
+        XHTMLOptions options = XHTMLOptions.create();
+            //获取文档中的图片
+        //List<XWPFPictureData> allPictures = docxDocument.getAllPictures();
+        //for (XWPFPictureData xwpfPictureData : allPictures) {
+        //    String name = xwpfPictureData.getFileName();
+        //    byte[] data = xwpfPictureData.getData();
+        //    InputStream input = new ByteArrayInputStream(data);
+        //    TODO 图片处理
+        //
+        //}
+        //final String imageUrl = "";
+        //不把图片生成出来
+        options.setExtractor(null);
+        options.setIgnoreStylesIfUnused(false);
+        options.setFragment(true);
+        //options.URIResolver(new IURIResolver() {
+        //    @Override
+        //    public String resolve(String uri) {
+        //        return imageUrl + uri;
+        //    }
+        //});
+        // 图片转base64 新版本支持
+        options.setImageManager(new Base64EmbedImgManager());
+         //转换htm1
+        ByteArrayOutputStream htmlStream = new ByteArrayOutputStream();
+        XHTMLConverter.getInstance().convert(docxDocument, htmlStream, options);
+        htmlData = htmlStream.toString();
+        htmlStream.close();
+        } catch(Exception e) {
+            e.printStackTrace();
+        }
+        return htmlData;
+    }
+
+    /**
+     * 图片处理
+     */
+    public class ImageConverter extends WordToHtmlConverter {
+
+        public ImageConverter(Document document) {
+            super(document);
+        }
+
+        @Override
+        protected void processImageWithoutPicturesManager(Element currentBlock, boolean inlined, Picture picture) {
+            Element imgNode = currentBlock.getOwnerDocument().createElement("img");
+            StringBuffer sb = new StringBuffer();
+            sb.append(Base64.getMimeEncoder().encodeToString(picture.getRawContent()));
+            sb.insert(0, "data:" + picture.getMimeType() + ";base64,");
+            imgNode.setAttribute("src", sb.toString());
+            currentBlock.appendChild(imgNode);
+        }
+    }
+}