Przeglądaj źródła

文件上传指定服务器工具类

user5 4 lat temu
rodzic
commit
9b2e003841

+ 12 - 0
pom.xml

@@ -1025,6 +1025,18 @@
             <artifactId>junrar</artifactId>
             <version>0.7</version>
         </dependency>
+
+        <!-- 文件上传附件到指定服务器目录 -->
+        <dependency>
+            <groupId>ch.ethz.ganymed</groupId>
+            <artifactId>ganymed-ssh2</artifactId>
+            <version>build250</version>
+        </dependency>
+        <dependency>
+            <groupId>com.jcraft</groupId>
+            <artifactId>jsch</artifactId>
+            <version>0.1.55</version>
+        </dependency>
     </dependencies>
 
 </project>

+ 70 - 1
src/main/java/com/jeeplus/common/bos/BosController.java

@@ -1,7 +1,7 @@
 package com.jeeplus.common.bos;
 
 import com.jeeplus.common.utils.FtlUtils;
-import com.jeeplus.modules.iim.entity.MailPage;
+import com.jeeplus.modules.utils.SftpClientUtil;
 import org.springframework.mock.web.MockMultipartFile;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -10,6 +10,7 @@ import org.springframework.web.multipart.MultipartFile;
 
 import javax.servlet.http.HttpServletRequest;
 import java.io.*;
+import java.util.Calendar;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -121,4 +122,72 @@ public class BosController {
         return map;
     }
 
+    @RequestMapping("uploadAssignServer")
+    @ResponseBody
+    public Map uploadAssignServer(MultipartFile file){
+        Map map = new HashMap();
+        try {
+            //MultipartFile转File
+            File srcFile = transformMultipartFile(file);
+            SftpClientUtil fileUploadUtil = new SftpClientUtil();
+            Calendar date = Calendar.getInstance();
+            String year = String.valueOf(date.get(Calendar.YEAR));
+            String month = String.valueOf(date.get(Calendar.MONTH)+1);
+            String day = String.valueOf(date.get(Calendar.DAY_OF_MONTH));
+            String uploadPath = "/"+year+"/"+month+"/"+day;
+            String uploadFile = fileUploadUtil.uploadFile(uploadPath, srcFile, srcFile.getName());
+            map.put("msg","上传成功");
+            map.put("code","1");
+            map.put("url",uploadFile);
+        } catch (Exception e) {
+            e.printStackTrace();
+            map.put("msg","上传失败");
+            map.put("code","0");
+        }
+        return map;
+    }
+
+
+
+    /**
+     * 获取流文件
+     * @param ins
+     * @param file
+     */
+    public static void inputStreamToFile(InputStream ins, File file) {
+        try {
+            OutputStream os = new FileOutputStream(file);
+            int bytesRead = 0;
+            byte[] buffer = new byte[8192];
+            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
+                os.write(buffer, 0, bytesRead);
+            }
+            os.close();
+            ins.close();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * MultipartFile转File
+     * @param file
+     * @return
+     * @throws IOException
+     */
+    public static File transformMultipartFile( MultipartFile file) throws IOException {
+        File srcFile = null;
+        //MultipartFile转File
+        if (file.equals("") || file.getSize() <= 0) {
+            file = null;
+        } else {
+            InputStream ins = null;
+            ins = file.getInputStream();
+            srcFile = new File(file.getOriginalFilename());
+            inputStreamToFile(ins, srcFile);
+            ins.close();
+        }
+        return srcFile;
+    }
+
 }

+ 2 - 1
src/main/java/com/jeeplus/modules/sys/utils/UserUtils.java

@@ -788,7 +788,8 @@ public class UserUtils {
 	 */
 	public static List<Area> getAreaList(){
 		@SuppressWarnings("unchecked")
-		List<Area> areaList = (List<Area>)getCache(CACHE_AREA_LIST);
+		//List<Area> areaList = (List<Area>)getCache(CACHE_AREA_LIST);
+		List<Area> areaList = null;
 		if (areaList == null){
 			areaList = areaDao.findAllList(new Area());
 			putCache(CACHE_AREA_LIST, areaList);

+ 236 - 0
src/main/java/com/jeeplus/modules/utils/SftpClientUtil.java

@@ -0,0 +1,236 @@
+package com.jeeplus.modules.utils;
+
+import java.io.*;
+import java.net.URLEncoder;
+import java.util.Properties;
+
+import com.jcraft.jsch.*;
+import com.jeeplus.common.config.Global;
+import org.apache.log4j.Logger;
+
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * @author: 徐滕
+ * @create: 2021-01-25 09:26
+ **/
+public class SftpClientUtil {
+    protected static Logger logger = Logger.getLogger(SftpClientUtil.class);
+
+    /** 主机 */
+    private final static String host = Global.getConfig("remoteServer.host");
+    /** 端口 */
+    private final static int port = Integer.parseInt(Global.getConfig("remoteServer.port"));
+    /** 用户名 */
+    private final static String username =  Global.getConfig("remoteServer.username");
+    /** 密码 */
+    private final static String password = Global.getConfig("remoteServer.password");
+    /** 目录 */
+    private final static String directory = Global.getConfig("remoteServer.directory");
+
+
+    /**
+     * 上传单个文件
+     * @param remoteFolder
+     *            上传到SFTP服务器的路径
+     * @param file
+     *            上传的文件
+     * @param remoteFileName
+     *            上传到SFTP服务器后的文件名
+     *
+     * @throws Exception
+     */
+    public String uploadFile(String remoteFolder,File file, String remoteFileName) throws Exception {
+        long start = System.currentTimeMillis();
+        remoteFolder = directory + remoteFolder;
+        InputStream fileStream = new FileInputStream(file); // 提升作用域
+        ChannelSftp sftp = connect();
+        try{
+            //判断上传文件路径是否存在
+            if(this.booleanUrl(remoteFolder,sftp)){
+                //不存在则创建文件路径
+                this.createDir(remoteFolder,sftp);
+            }
+            //如果文件夹不存在,则创建文件夹
+            if(sftp.ls(remoteFolder) == null){
+                sftp.mkdir(remoteFolder);
+            }
+            //切换到指定文件夹
+            sftp.cd(remoteFolder);
+        }catch (SftpException e){
+        }
+        sftp.put(fileStream, remoteFileName);
+        disconnect(sftp);
+        logger.info("文件上传成功!! 耗时:{"+(System.currentTimeMillis() - start)+"}ms");
+        return remoteFolder+"/"+remoteFileName;
+    }
+
+    /**
+     * 删除文件
+     * @param deleteFile
+     *            要删除的文件
+     *
+     * @throws Exception
+     */
+    public void delete(String deleteFile) throws Exception {
+        ChannelSftp sftp = connect();
+        sftp.cd(directory);
+        sftp.rm(deleteFile);
+        disconnect(sftp);
+    }
+
+    /**
+     * 连接sftp服务器
+     *
+     * @throws Exception
+     */
+    public static ChannelSftp connect() throws Exception {
+        JSch jsch = new JSch();
+        try{
+            //采用指定的端口连接服务器
+            Session session = jsch.getSession(username,host,port);
+            if(password != null){
+                //设置登陆主机的密码
+                session.setPassword(password);
+            }
+
+            Properties sshConfig = new Properties();
+            sshConfig.put("StrictHostKeyChecking", "no");
+            session.setConfig(sshConfig);
+            session.connect();
+
+            //创建sftp通信通道
+            Channel channel = session.openChannel("sftp");
+            channel.connect();
+            logger.info("sftp server connect success !!");
+            return (ChannelSftp) channel;
+        }catch (JSchException e){
+            logger.error("SFTP服务器连接异常!!", e);
+            throw new Exception("SFTP服务器连接异常!!",e);
+        }
+    }
+
+
+    /**
+     * Disconnect with server
+     *
+     * @throws Exception
+     */
+    public static void disconnect(ChannelSftp sftp) {
+        if (sftp != null) {
+            if (sftp.isConnected()) {
+                sftp.disconnect();
+            } else if (sftp.isClosed()) {
+            }
+        }
+    }
+
+    /**
+     * 检测文件夹是否存在
+     *
+     * @param directory     路径
+     * @return
+     */
+    public boolean booleanUrl(String directory,ChannelSftp sftp){
+        try{
+            if(sftp.ls(directory) == null){
+                return false;
+            }
+        }catch (Exception e){
+            logger.error("检测文件夹异常!", e);
+        }
+        return true;
+    }
+
+    /**
+     * 创建一个文件目录
+     *
+     * @param createpath        路径
+     * @return
+     */
+    public boolean createDir(String createpath,ChannelSftp sftp) {
+        try {
+            if (isDirExist(createpath,sftp)) {
+                sftp.cd(createpath);
+                return true;
+            }
+            String pathArry[] = createpath.split("/");
+            StringBuffer filePath = new StringBuffer("/");
+            for (String path : pathArry) {
+                if (path.equals("")) {
+                    continue;
+                }
+                filePath.append(path + "/");
+                if (isDirExist(filePath.toString(),sftp)) {
+                    sftp.cd(filePath.toString());
+                } else {
+                    // 建立目录
+                    sftp.mkdir(filePath.toString());
+                    // 进入并设置为当前目录
+                    sftp.cd(filePath.toString());
+                }
+            }
+            sftp.cd(createpath);
+        } catch (SftpException e) {
+            logger.error("目录创建异常!", e);
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * 判断目录是否存在
+     *
+     * @param directory     路径
+     * @return
+     */
+    public boolean isDirExist(String directory,ChannelSftp sftp) {
+        boolean isDirExistFlag = false;
+        try {
+            SftpATTRS sftpATTRS = sftp.lstat(directory);
+            isDirExistFlag = true;
+            return sftpATTRS.isDir();
+        } catch (Exception e) {
+            if (e.getMessage().toLowerCase().equals("no such file")) {
+                isDirExistFlag = false;
+            }
+        }
+        return isDirExistFlag;
+    }
+
+    /**
+     * 下载文件
+     *
+     * @param directory     SFTP服务器的文件路径
+     * @param downloadFile  SFTP服务器上的文件名
+     * @return              字节数组
+     */
+    public byte[] download(String directory, String downloadFile, HttpServletResponse response){
+        try{
+            ChannelSftp sftp = connect();
+            if(directory != null && !"".equals(directory)){
+                sftp.cd(directory);
+            }
+            String fileName = URLEncoder.encode(downloadFile,"UTF-8");
+            OutputStream out = null;
+            InputStream in = sftp.get(downloadFile);
+            response.reset();//重置 响应头
+            response.setContentType("application/x-download");
+            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
+            out = response.getOutputStream();
+            byte[] b = new byte[1024];
+            int len;
+            while ((len = in.read(b)) > 0){
+                response.getOutputStream().write(b, 0, len);
+            }
+            in.close();
+            out.close();
+        }catch (SftpException | IOException e){
+            logger.error("文件下载异常!", e);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+}
+

+ 13 - 1
src/main/resources/jeeplus.properties

@@ -257,4 +257,16 @@ backUrl = http://yf.xgccpm.cn/weXin/theOrder/orderFrom
 windowsPath = d:/simple/
 
 #公告linux上传路径
-linuxPath = /simple/
+linuxPath = /simple/
+
+#文件上传服务器信息
+#主机
+remoteServer.host = 192.168.2.4
+#端口
+remoteServer.port = 22
+#用户名
+remoteServer.username =root
+#密码
+remoteServer.password =asd1234567@
+#目录
+remoteServer.directory =/simple