sftp 服务器搭建及 文件下载与上传

// controller方法**********************************************************************************************************************************************************************

@Controller
@RequestMapping(value="${adminPath}/realUserMaterial/realUserMaterial")
public class RealUserMaterialController extends BaseController{
@Autowired
private RealUserMaterialService realUserMaterialService;
private UserMaterialService userMaterialService;

//材料下载
@ResponseBody
@RequestMapping(value="realUserMaterialDown")
public void realUserMaterialDown(@RequestParam(required=false) String id,HttpServletResponse response,HttpServletRequest request) throws IOException{
RealUserMaterial realUserMaterial = null;
if(StringUtils.isNotBlank(id)){
realUserMaterial = realUserMaterialService.get(id);
}
if(null != realUserMaterial){
String fileAddress = realUserMaterial.getFileAddress();
    String fileNamelocal = realUserMaterial.getFileName();
 
byte[] fileContent = UploadFileToServer.downloadFile(fileNamelocal, fileAddress, request);
// 以流的形式下载文件
       response.setContentType("application/octet-stream");
       response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileNamelocal.getBytes("gb2312"), "ISO8859-1" ) + "\"");
       OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
       toClient.write(fileContent);
       toClient.flush();
       toClient.close();

}

       //上传
@ResponseBody
@RequestMapping(value="save")
public String save(UserMaterial userMaterial,MultipartFile file, HttpSession session,HttpServletRequest request){
String id = userMaterial.getId();
try{
userMaterial.setMaterialName(MultipartFileUtil.getfileName(file));
String fileName1=file.getOriginalFilename();
String filehz=fileName1.substring(fileName1.lastIndexOf("."));
String fileName=UserUtils.getUser().getId()+new Date().getTime()+filehz;
   byte[] fileEntity=file.getBytes(); 
   UploadFileToServer.uploadFile(fileName, fileEntity, request);

                    //获取 项目propleties配置文件
   userMaterial.setFileAddress(Global.getConfig("fileServerUploadPath") + fileName);

UserMaterial temp = userMaterialService.findByidCardAndMaterialid(userMaterial.getUserIdCard(), userMaterial.getUserType(), userMaterial.getMaterialId());
if(null != temp){
userMaterial.setId(temp.getId());
id = temp.getId();
}
if(null != id && !"".equals(id)){
return userMaterialService.update(userMaterial);//保存
} else {
userMaterialService.save(userMaterial);
return userMaterial.getId();
}
} catch(Exception e){
e.printStackTrace();
return "fail";
}
}

}



//一层工具类******************************************************************************************************************************************************************

package com.jeeplus.common.utils;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import com.jeeplus.common.config.Global;

import com.jeeplus.modules.material.util.demo;

//上传文件至ftp服务器

public class UploadFileToServer{
private static String fileServerPath = Global.getConfig("fileServerPath"); // 文件服务器地址
private static String fileServerPort = Global.getConfig("fileServerPort"); // 文件服务器端口
private static String fileServerUserName = Global.getConfig("fileServerUserName"); // 文件服务器用户名
private static String fileServerPassword = Global.getConfig("fileServerPassword"); // 文件服务器密码
private static String fileServerUploadPath = Global.getConfig("fileServerUploadPath"); // 文件服务器上传地址

//文件上传
public static void uploadFile(String fileName, byte[] fileEntity, String filepath){
  FileOutputStream fos=null;
  File file=new File(filepath);
  if(!file.exists()){
  file.mkdir();
  }
  String filepathff=filepath+ File.separator+fileName;
  System.out.println(File.separator);
if(fileEntity.length!=0){
file = new File(filepathff); 
try {
fos = new FileOutputStream(file);
fos.write(fileEntity, 0, fileEntity.length);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
  demo.sftpUpload(fileServerPath, fileServerPort, fileServerUserName, fileServerPassword, fileServerUploadPath, fileName, filepath, fileName);
      file.delete();
}
}

//文件上传
public static void uploadFile(String fileName, byte[] fileEntity, HttpServletRequest request){
String filepath = request.getSession().getServletContext().getRealPath("/upload"); 
  FileOutputStream fos=null;
  File file=new File(filepath);
  if(!file.exists()){
  file.mkdir();
  }
  String filepathff=filepath + File.separator + fileName;
if(fileEntity.length!=0){
file = new File(filepathff); 
try {
fos = new FileOutputStream(file);
fos.write(fileEntity, 0, fileEntity.length);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
  demo.sftpUpload(fileServerPath, fileServerPort, fileServerUserName, fileServerPassword, fileServerUploadPath, fileName, filepath, fileName);
      file.delete();
}
}

//文件下载(二进制流)
public static byte[] downloadFile(String fileName, String filepath,HttpServletRequest request){
String path = request.getSession().getServletContext().getRealPath("/downloadTemp"); 
String filepathserver = filepath.substring(0, filepath.lastIndexOf("/"));
   String fileNameserver = filepath.substring(filepath.lastIndexOf("/"));
   File file=new File(path);
   if(!file.exists()){
  file.mkdir();
   }
   demo.sftpDownload(fileServerPath, fileServerPort, fileServerUserName, fileServerPassword, filepathserver, fileNameserver, path, fileName);
   file = new File(path + File.separator + fileName);
   byte[] fileContent = File2byte(file);
   boolean flag = false;
   while(!flag){
    flag = file.delete();
   }
   return fileContent;
}

//将文件转为二进制
public static byte[] File2byte(File file) {  
        byte[] buffer = null;  
        try {  
            FileInputStream fis = new FileInputStream(file);  
            ByteArrayOutputStream bos = new ByteArrayOutputStream();  
            byte[] b = new byte[1024];  
            int n;  
            while ((n = fis.read(b)) != -1)  {  
                bos.write(b, 0, n);  
            }  
            fis.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        }  catch (FileNotFoundException e)  {  
            e.printStackTrace();  
        }  catch (IOException e)  {  
            e.printStackTrace();  
        }  
        return buffer;  
    }  

}





//二层工具类****************************************************************************************************************************************************************************

package com.jeeplus.modules.material.util;

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; 
import org.apache.log4j.Logger;
import com.jcraft.jsch.Channel; 
import com.jcraft.jsch.ChannelSftp; 
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException; 


public class demo {


private static final Logger logger = Logger.getLogger(demo.class);

/**
* <p>Description: SFTP协议下载文件</p>
* @param ip  SFTP服务器IP地址
* @param port  SFTP服务器端口  22
* @param username  SFTP服务器登录用户名
* @param password  SFTP服务器登录密码
* @param remoteFilePath  SFTP服务器文件存放目录
* @param remoteFileName  SFTP服务器需要下载的文件名
* @param localFilePath  需要下载到本地的路径
* @param localFileName  需要下载到本地的文件名
* @return
* @author tt 
* @date 2017年5月11日下午7:06:12
*/
public static Map<String,String> sftpDownload(String ip, String port, String username, String password, String remoteFilePath, 
String remoteFileName, String localFilePath, String localFileName) {

Map<String,String> resultMap = new HashMap<String,String>();
//连接SFTP文件服务器
ChannelSftp sftp = getSFTPConnect(ip, Integer.parseInt(port), username, password);
try {
String filePath = remoteFilePath;
String downFilePath = parsePath(remoteFilePath + File.separator + remoteFileName);
sftp.cd(filePath);
if (localFileName == null || "".equals(localFileName)) {
localFileName = remoteFileName;
}
String saveFilePath = parsePath(localFilePath + File.separator + localFileName);
File file = new File(saveFilePath);
//将获取到的文件信息存入 本地下载路径
sftp.get(downFilePath, new FileOutputStream(file));
resultMap.put("filePath", saveFilePath);
} catch (Exception e) {
logger.error("SFTP下载异常", e);
} finally {
//关闭连接SFTP文件服务器
if (sftp != null) {
sftp.disconnect();
}
}
return resultMap;
}

/**
* <p>Description: 获取SFTP连接</p>
* @param host  SFTP服务器IP地址
* @param port  SFTP服务器端口
* @param username  SFTP服务器登录用户名
* @param password  SFTP服务器登录密码
* @return
* @author tt 
* @date 2017年5月11日下午6:24:45
*/
public static ChannelSftp getSFTPConnect(String ip, int port, String username, String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, ip, port);
Session sshSession = jsch.getSession(username, ip, port);
logger.debug("Session created.");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
logger.debug("Session connected.");
logger.debug("Opening Channel.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
logger.debug("Connected to " + ip + ".");
// 登录成功
} catch (Exception e) {
logger.error("获取SFTP连接异常", e);
}
return sftp;
}

/**

* <p>Description: 格式化路径</p>
* @param path
* @return
* @author tt 
* @date 2017年5月11日下午6:44:14
*/
public static String parsePath(String path) {
path = path.replace("//", "/");
path = path.replace("\\", "/");
String parsePath = "";
while (true) {
path = path.replace("//", "/");
path = path.replace("\\", "/");
parsePath = path.replace("//", "/");
parsePath = path.replace("\\", "/");
if (!path.contains("//") && !path.contains("\\")) {
break;
}
}
return parsePath;
}

/**
* <p>Description: 根据文件完整路径URL获取文件信息</p>
* @param url  文件完整路径
* @return map:fileName/filePath/shortFileName/suffix
* @author tt 
* @date 2017年5月15日上午9:51:01
*/
public static Map<String, String> getFileInfoMap(String url) {
url = url.replace("/", File.separator);
Map<String, String> map = new HashMap<String, String>();
String fileName = url.substring(url.lastIndexOf(File.separator) + 1);
String filePath = url.substring(0, url.lastIndexOf(File.separator));
String shortFileName = fileName.indexOf(".") > -1 ? fileName.substring(0, fileName.lastIndexOf(".")) : fileName;
String suffix = fileName.indexOf(".") > -1 ? fileName.substring(fileName.lastIndexOf(".") + 1) : "";
// C:\\abc.txt
// 文件名称abc.txt
map.put("fileName", fileName);
// 文件路径C:\\
map.put("filePath", filePath);
// 文件前缀名abc
map.put("shortFileName", shortFileName);
// 文件后缀txt
map.put("suffix", suffix);
return map;
}

/**
* <p>Description: 判断文件夹是否存在</p>
* @param directory  目录名称
* @param sftp
* @return
* @author tt 
* @date 2017年5月16日上午10:36:45
*/
public static 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;
}

/**
* <p>Description: SFTP协议上传文件</p>
* @param ip  SFTP服务器IP地址
* @param port  SFTP服务器端口
* @param username  SFTP服务器登录用户名
* @param password  SFTP服务器登录密码
* @param remoteFilePath  SFTP服务器文件存放目录
* @param remoteFileName  给上传到SFTP服务器的文件命名
* @param localFilePath  本地文件路径
* @param localFileName  本地文件名
* @return
* @author tt 
* @date 2017年5月11日下午7:06:12
*/
public static Map<String,String> sftpUpload(String ip, String port, String username, String password, String remoteFilePath, 
String remoteFileName, String localFilePath, String localFileName) {

Map<String,String> resultMap = new HashMap<String,String>();
//连接SFTP文件服务器
ChannelSftp sftp = getSFTPConnect(ip, Integer.parseInt(port), username, password);
FileInputStream in = null;
try {
sftp.cd(remoteFilePath);
if (remoteFileName == null || "".equals(remoteFileName)) {
remoteFileName = localFileName;
}
String uploadFilePath = parsePath(remoteFilePath + File.separator + remoteFileName);
File file = new File(parsePath(localFilePath + File.separator + localFileName));
// 上传文件夹
if (file.isDirectory()) {
File[] fileList = file.listFiles();
try {
sftp.cd(file.getName());
} catch (SftpException e) {
sftp.mkdir(file.getName());
sftp.cd(file.getName());
}
for (int i = 0; i < fileList.length; i++) {
String uploadPath = parsePath(uploadFilePath + File.separator + fileList[i].getName());
in = new FileInputStream(fileList[i]);
sftp.put(in, uploadPath);
in.close();
           }
} else {
// 上传文件
in = new FileInputStream(file);
sftp.put(in, uploadFilePath);
}
resultMap.put("filePath", uploadFilePath);
} catch (Exception e) {
logger.error("SFTP上传异常", e);
} finally {
if (sftp != null) {
                sftp.disconnect();
                try {
                sftp.getSession().disconnect();
                } catch (JSchException e) {
                e.printStackTrace();
                }
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return resultMap;
}
}




//全局工具类 2个*************************************************************************************************************************************************************

/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.common.config;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
import java.util.Properties;
import org.apache.ibatis.io.Resources;
import org.springframework.core.io.DefaultResourceLoader;
import com.ckfinder.connector.ServletContextFactory;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.PropertiesLoader;
import com.jeeplus.common.utils.StringUtils;


/**
 * 全局配置类
 * @author jeeplus
 * @version 2014-06-25
 */
public class Global {


/**
* 当前对象实例
*/
private static Global global = new Global();

/**
* 保存全局属性值
*/
private static Map<String, String> map = Maps.newHashMap();

/**
* 属性文件加载对象
*/
private static PropertiesLoader loader = new PropertiesLoader("jeeplus.properties");


/**
* 显示/隐藏
*/
public static final String SHOW = "1";
public static final String HIDE = "0";


/**
* 是/否
*/
public static final String YES = "1";
public static final String NO = "0";

/**
* 对/错
*/
public static final String TRUE = "true";
public static final String FALSE = "false";

/**
* 上传文件基础虚拟路径
*/
public static final String USERFILES_BASE_URL = "/userfiles/";

/**
* 获取当前对象实例
*/
public static Global getInstance() {
return global;
}

/**
* 获取配置
* @see ${fns:getConfig('adminPath')}
*/
public static String getConfig(String key) {
String value = map.get(key);
if (value == null){
value = loader.getProperty(key);
map.put(key, value != null ? value : StringUtils.EMPTY);
}
return value;
}

/**
* 获取管理端根路径
*/
public static String getAdminPath() {
return getConfig("adminPath");
}

/**
* 获取前端根路径
*/
public static String getFrontPath() {
return getConfig("frontPath");
}

/**
* 获取URL后缀
*/
public static String getUrlSuffix() {
return getConfig("urlSuffix");
}

/**
* 是否是演示模式,演示模式下不能修改用户、角色、密码、菜单、授权
*/
public static Boolean isDemoMode() {
String dm = getConfig("demoMode");
return "true".equals(dm) || "1".equals(dm);
}

/**
* 在修改系统用户和角色时是否同步到Activiti
*/
public static Boolean isSynActivitiIndetity() {
String dm = getConfig("activiti.isSynActivitiIndetity");
return "true".equals(dm) || "1".equals(dm);
}
    
/**
* 页面获取常量
* @see ${fns:getConst('YES')}
*/
public static Object getConst(String field) {
try {
return Global.class.getField(field).get(null);
} catch (Exception e) {
// 异常代表无配置,这里什么也不做
}
return null;
}


/**
* 获取上传文件的根目录
* @return
*/
public static String getUserfilesBaseDir() {
String dir = getConfig("userfiles.basedir");
if (StringUtils.isBlank(dir)){
try {
dir = ServletContextFactory.getServletContext().getRealPath("/");
} catch (Exception e) {
return "";
}
}
if(!dir.endsWith("/")) {
dir += "/";
}
// System.out.println("userfiles.basedir: " + dir);
return dir;
}

    /**
     * 获取工程路径
     * @return
     */
    public static String getProjectPath(){
    // 如果配置了工程路径,则直接返回,否则自动获取。
String projectPath = Global.getConfig("projectPath");
if (StringUtils.isNotBlank(projectPath)){
return projectPath;
}
try {
File file = new DefaultResourceLoader().getResource("").getFile();
if (file != null){
while(true){
File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
if (f == null || f.exists()){
break;
}
if (file.getParentFile() != null){
file = file.getParentFile();
}else{
break;
}
}
projectPath = file.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return projectPath;
    }
    
    /**
* 写入properties信息

* @param key
*            名称
* @param value
*            值
*/
public static void modifyConfig(String key, String value) {
try {
// 从输入流中读取属性列表(键和元素对)
Properties prop = getProperties();
prop.setProperty(key, value);
String path = Global.class.getResource("/jeeplus.properties").getPath();
FileOutputStream outputFile = new FileOutputStream(path);
prop.store(outputFile, "modify");
outputFile.close();
outputFile.flush();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 返回 Properties
* @param fileName 文件名 (注意:加载的是src下的文件,如果在某个包下.请把包名加上)
* @param 
* @return
*/
public static Properties getProperties(){
Properties prop = new Properties();
try {
Reader reader = Resources.getResourceAsReader("/jeeplus.properties");
prop.load(reader);
} catch (Exception e) {
return null;
}
return prop;
}
}


// propleties配置文件********************************************************************************************************************************************************

fileServerPath=127.0.0.1
fileServerPort=22
fileServerUserName=username
fileServerPassword=password
fileServerUploadPath=/               #该路径是在ftp服务器根目录基础上的路径,比如 若ftp服务器根目录为F:/ftp/upload,此处只需配置路径为‘/’


//另外说明:*****************************************************************************************************************************************************************

使用ftp 工具为Serv-U,博客内我有上传;

jeeplus为我的项目名;


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值