您的位置:首页 > 编程语言 > PHP开发

sftpII

2015-11-23 14:50 696 查看
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;

@Controller
public class SftpController {

private  static final  Log logger = org.apache.commons.logging.LogFactory.getLog(SftpController.class);

@Autowired
private SFTPChannel channel   ;

@ResponseBody
@RequestMapping(value="/sftp/upload" , produces="text/html;charset=UTF-8")
public  String upLoad(@RequestParam("file") MultipartFile[] files  ,
@RequestParam("host") String host ,
@RequestParam("port") String port ,
@RequestParam("username") String username ,
@RequestParam("password") String password ,
@RequestParam("targetPath") String targetPath ) throws Exception{

JSONObject responseStr  =  new JSONObject() ;

Map<String, String> sftpDetails = new HashMap<String, String>();
// 设置主机ip,端口,用户名,密码
sftpDetails.put(SFTParam.SFTP_REQ_HOST, host) ;
sftpDetails.put(SFTParam.SFTP_REQ_USERNAME, username) ;
sftpDetails.put(SFTParam.SFTP_REQ_PASSWORD, password) ;
sftpDetails.put(SFTParam.SFTP_REQ_PORT, port) ;
sftpDetails.put(SFTParam.SFTP_TARGET_PATH, targetPath) ;

logger.info("Processing [upLoad] msg, request parameters:"+JSON.toJSONString(sftpDetails));

ChannelSftp chSftp = new ChannelSftp() ;
try{
chSftp = channel.getChannel(sftpDetails, 600) ;
}catch(JSchException e){
responseStr.put("retCode", "9999") ;
responseStr.put("retMsg", "连接不上sftp!") ;
chSftp.quit();
channel.closeChannel();
return responseStr.toJSONString()  ;
}

try{
int k =  0 ;
for(MultipartFile file : files){
String fileName = file.getOriginalFilename();
if(fileName == null || fileName.equals(""))  continue ;

createDir(chSftp , targetPath)   ;

k++ ;
String dst = targetPath + "/" + fileName      ;
chSftp.put(file.getInputStream() , dst , new FileProgressMonitor(file.getSize()), ChannelSftp.OVERWRITE);
}

if(k == 0){
responseStr.put("retCode", "9999") ;
responseStr.put("retMsg", "上传文件不能为空!") ;
logger.info("Processing [upLoad] msg, 上传文件为空!" );
return responseStr.toJSONString()  ;
}
}catch(SftpException e){
responseStr.put("retCode", "9999") ;
responseStr.put("retMsg", "上传失败!") ;
chSftp.quit();
channel.closeChannel();
return responseStr.toJSONString()  ;
}

chSftp.quit();
channel.closeChannel();
responseStr.put("retCode", "0000") ;
responseStr.put("retMsg", "") ;

return responseStr.toJSONString()  ;
}

@RequestMapping(value="/sftp/download" , produces="text/html;charset=UTF-8")
@ResponseBody
public void download(@RequestParam("host") String host ,
@RequestParam("port") String port ,
@RequestParam("username") String username ,
@RequestParam("password") String password ,
@RequestParam("targetPath") String targetPath ,
HttpServletResponse response) throws Exception {

Map<String, String> sftpDetails = new HashMap<String, String>();
ChannelSftp chSftp = null   ;
String dst = null ;
OutputStream out ;

String realName = targetPath.substring(targetPath.lastIndexOf("/")  + 1 )  ;
// 设置主机ip,端口,用户名,密码
sftpDetails.put(SFTParam.SFTP_REQ_HOST, host) ;
sftpDetails.put(SFTParam.SFTP_REQ_USERNAME, username) ;
sftpDetails.put(SFTParam.SFTP_REQ_PASSWORD, password) ;
sftpDetails.put(SFTParam.SFTP_REQ_PORT, port) ;
sftpDetails.put(SFTParam.SFTP_TARGET_PATH, targetPath) ;

logger.info("Processing [download] msg, request parameters:"+JSON.toJSONString(sftpDetails));

try{
chSftp = channel.getChannel(sftpDetails, 6000)  ;
SftpATTRS attr = chSftp.stat(targetPath) ;
long fileSize = attr.getSize() ;
dst =  realName   ;
out = new FileOutputStream(dst) ;
chSftp.get(targetPath, out, new FileProgressMonitor(fileSize)) ;
}
catch (Exception e){
if(chSftp != null) chSftp.quit();
channel.closeChannel();
logger.info("Processing [download] msg, 连接不上sfpt!") ;
}
finally{
if(chSftp != null) chSftp.quit();
channel.closeChannel();
}

File file = new File(dst);
int BUFFER_SIZE = 4096;
InputStream in = null;
OutputStream out2 = null;
try{
response.setHeader("retcode", "0000") ;
response.setCharacterEncoding("utf-8") ;
response.setHeader("Content-disposition", "attachment; filename= "  + realName )  ;
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Accept-Ranges", "bytes");
in = new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE);
out2 = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[BUFFER_SIZE];
int readLength = 0;
while ((readLength=in.read(buffer)) > 0) {
byte[] bytes = new byte[readLength];
System.arraycopy(buffer, 0, bytes, 0, readLength);
out2.write(bytes);
}
out2.flush();
}
catch(Exception e){
logger.info("Processing [download] msg, 文件转换失败!") ;
throw e ;
}
finally
{
if (in != null)
{
try {
in.close();
} catch (IOException e) {
throw e ;
}
}

if (out2 != null) {
try {
out2.close();
} catch (IOException e) {
throw e ;
}
}

}

file.delete()  ;
}

@RequestMapping(value="/sftp/downloadCheck" , produces="text/html;charset=UTF-8")
@ResponseBody
public String candownload(@RequestParam("host") String host ,
@RequestParam("port") String port ,
@RequestParam("username") String username ,
@RequestParam("password") String password ,
@RequestParam("targetPath") String targetPath ) throws Exception{

JSONObject responseStr  =  new JSONObject() ;
Map<String, String> sftpDetails = new HashMap<String, String>();
// 设置主机ip,端口,用户名,密码
sftpDetails.put(SFTParam.SFTP_REQ_HOST, host) ;
sftpDetails.put(SFTParam.SFTP_REQ_USERNAME, username) ;
sftpDetails.put(SFTParam.SFTP_REQ_PASSWORD, password) ;
sftpDetails.put(SFTParam.SFTP_REQ_PORT, port);
sftpDetails.put(SFTParam.SFTP_TARGET_PATH, targetPath) ;

logger.info("Processing [candownload] msg, request parameters:"+JSON.toJSONString(sftpDetails));

ChannelSftp chSftp = new ChannelSftp()  ;
try{
chSftp = channel.getChannel(sftpDetails, 600)  ;
}
catch(JSchException e){
logger.info("Processing [candownload] msg, 连接不上sfpt!") ;
responseStr.put("retCode", "9999") ;
responseStr.put("retMsg", "连接不上sftp!") ;
chSftp.quit() ;
return  responseStr.toJSONString()  ;
}

SftpATTRS attr  ;
try{
attr = chSftp.stat(targetPath) ;
}
catch(SftpException e){
responseStr.put("retCode", "9999") ;
responseStr.put("retMsg", "没有此文件,下载失败!") ;
chSftp.quit() ;
logger.info("Processing [candownload] msg, 没有要下载的文件!") ;
return  responseStr.toJSONString()  ;
}

chSftp.quit();
channel.closeChannel();

responseStr.put("retCode", "0000") ;
responseStr.put("retMsg", "")  ;
return  responseStr.toJSONString()  ;
}

/**
* 创建目录
*
* @param createpath
* @return
*/
public boolean createDir(ChannelSftp sftp , String createpath) {
try {
if (isDirExist(sftp , createpath)) {
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(sftp , filePath.toString())) {
sftp.cd(filePath.toString());
} else {
// 建立目录
sftp.mkdir(filePath.toString());
// 进入并设置为当前目录
sftp.cd(filePath.toString());
}

}
sftp.cd(createpath);
return true;
} catch (SftpException e) {
e.printStackTrace();
}
return false;
}

/**
* 判断目录是否存在
*
* @param directory
* @return
*/
public boolean isDirExist(ChannelSftp sftp , String directory) {
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: