记录一下从ftp服务器上下载文件和上传文件的代码,实现预览功能
首先需要写一个连接ftp服务的工具类
public class JschFtpUtil {
/**
* 获取sftp协议连接.
*
* @param host
* 主机名
* @param port
* 端口
* @param username
* 用户名
* @param password
* 密码
* @return 连接对象
* @throws JSchException
* 异常
*/
public static ChannelSftp getSftpConnect(final String host, final int port, final String username,
final String password) throws JSchException {
ChannelSftp sftp = null;
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("连接成功");
return sftp;
}
/**
* 删除文件-sftp协议.
*
* @param deleteFile
* 要删除的文件
* @param sftp
* sftp连接
* @throws Exception
* 异常
*/
public static void rmFile(final String deleteFile, final ChannelSftp sftp) throws Exception {
try {
sftp.rm(deleteFile);
} catch (Exception e) {
exit(sftp);
throw e;
}
}
/**
* 关闭协议-sftp协议.
*
* @param sftp
* sftp连接
*/
public static void exit(final ChannelSftp sftp) {
sftp.exit();
}
/** 通过sftp下载文件 **/
public static byte[] get(String remoteHost, int port, String remotePath, String remoteFileName, String user,
String password) {
JSch ftp = new JSch();
Channel channel = null;
Session session = null;
InputStream in = null;
byte[] bs = {};
try {
session = ftp.getSession(user, remoteHost, port);
if (password != null)
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
ChannelSftp channelSftp = (ChannelSftp) channel;
channelSftp.cd(remotePath);
in = channelSftp.get(remoteFileName);
bs = InputStreamToByte(in);
// System.out.println("bs is:"+bs);
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (channel != null)
channel.disconnect();
if (session != null)
session.disconnect();
}
return bs;
}
/** ftp上传。默认远程文件名称与本地文件名相同 **/
public static boolean put(String remoteHost, int port, String remotePath, String user, String password,
InputStream fileInputStream, String fileName) {
boolean result = false;
JSch ftp = new JSch();
Channel channel = null;
Session session = null;
try {
session = ftp.getSession(user, remoteHost, port);
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
ChannelSftp channelSftp = (ChannelSftp) channel;
try {
Vector vc = channelSftp.ls(remotePath); // 首先查看下目录,如果不存在,系统会被错,捕获这个错,生成新的目录。
logger.info("上传的文件目录是否存在:remotePath:{},isEmpty:{}", remotePath, vc.isEmpty());
} catch (Exception e) {
String filePath = "/";
String[] files = remotePath.split("\\/");
for (String fileStr : files) {
filePath += fileStr + "/";
try {
channelSftp.ls(filePath);
} catch (Exception e1) {
logger.info("上传的文件目录不存在:remotePath:{},创建一个新目录.", filePath);
channelSftp.mkdir(filePath);
}
}
}
channelSftp.cd(remotePath);
channelSftp.put(fileInputStream, fileName);
channel.disconnect();
session.disconnect();
logger.error("上传文件成功:{}", remotePath + fileName);
result = true;
} catch (Exception e) {
logger.error("上传文件失败:{},{}", remotePath + fileName, e);
} finally {
if (channel != null)
channel.disconnect();
if (session != null)
session.disconnect();
}
return result;
}
}
上传文件的方法
public void uploadingFile(String orderId,MultipartFile xslFile) {
TinsureSchemeOrder schemeOrder = getSchemeOrderInfo(orderId);
if (!xslFile.isEmpty()) {
String remotePath = ConfigConst.FTP_REMOTEPATH + BaseConst.WEBNAME + "/" + BaseConst.INSURE + "/"+orderId+"/";
String suffix = xslFile.getOriginalFilename();
String suffixName = suffix.substring(suffix.indexOf("."));
String fileName = orderId+new SimpleDateFormat("yyMMddHHmmss").format(new Date()) + suffixName;
try {
// 删除原来的老文件
String oldFileName = schemeOrder.getPolicyFilePath();
if(oldFileName !=null){
String name = oldFileName.substring( oldFileName.length()-26);
ChannelSftp sftp = JschFtpUtil.getSftpConnect(ConfigConst.FTP_REMOTEHOST, 22, ConfigConst.FTP_USER, ConfigConst.FTP_PASSWORD);
JschFtpUtil.rmFile(ConfigConst.FTP_REMOTEPATH + BaseConst.WEBNAME + "/" + BaseConst.INSURE + "/"+orderId+"/"+name, sftp);
sftp.exit();
}
InputStream idIO = xslFile.getInputStream();
boolean uploadResult = JschFtpUtil.put(ConfigConst.INNER_FTP_REMOTEHOST, ConfigConst.INNER_FTP_PORT, remotePath,
ConfigConst.INNER_FTP_USER, ConfigConst.INNER_FTP_PASSWORD, idIO, fileName);
if (!uploadResult) {
throw new BaseTxException("upload_fail", "文件上传失败,请重新提交");
}
schemeOrder.setPolicyFilePath(BaseConst.WEBNAME + "/" + BaseConst.INSURE + "/" + fileName);
tinsureSchemeOrderDao.updateSchemeOrderInfo(schemeOrder);
} catch (IOException e) {
throw new BaseTxException("upload_fail", "文件添加失败");
} catch (Exception e) {
System.out.println("文件删除失败!");
}
}
}
Controller类
@RequestMapping("/import")
public String import(Model model,TinsureSchemeOrder schemeOrder,@RequestParam(value = "xslFile") MultipartFile xslFile)throws BaseAppException {
insureSchemeOrderTxService.uploadingFile(schemeOrder.getOrderId(),xslFile);
return INSURE_LIST;
}
下载实现类
public void policyFile(String orderId,HttpServletResponse response,HttpServletRequest request) throws BaseAppException{
TinsureSchemeOrder schemeOrder = getSchemeOrderInfo(orderId);
String fileNames = schemeOrder.getPolicyFilePath();
String fileName = fileNames.substring( fileNames.length()-26);
String remotePath = ConfigConst.FTP_REMOTEPATH +BaseConst.WEBNAME + "/" + BaseConst.INSURE + "/"+orderId+"/";
BufferedOutputStream bos = null;
try {
byte[] buffer = JschFtpUtil.get(ConfigConst.INNER_FTP_REMOTEHOST,
ConfigConst.INNER_FTP_PORT, remotePath, fileName,
ConfigConst.INNER_FTP_USER, ConfigConst.INNER_FTP_PASSWORD);
if (buffer.length == 0) {
throw new Exception("从FTP获取对账文件失败:"+fileName);
}
bos = new BufferedOutputStream(response.getOutputStream());
response.setHeader("Content-disposition", "attachment;filename=" + CommonUtil.encodeFileName("保单详情"+fileName, request));
bos.write(buffer);
} catch (IOException e) {
logger.info(e.getMessage());
throw new BaseAppException("读取文件失败");
}catch(Exception e){
logger.info(e.getMessage());
throw new BaseAppException(e.getMessage());
}finally{
if(bos!=null){
try {
bos.flush();
bos.close();
} catch (IOException e) {
logger.info("关闭下载输出流失败");
}
}
}
}
Controller类
@RequestMapping("download")
public void download(String orderId,HttpServletResponse response,HttpServletRequest request) throws BaseAppException{
insureSchemeOrderTxService.policyFile(orderId, response, request);
}
预览文件,pdf文件或者图片
public void previewPolicyFile(String orderId,HttpServletResponse response,HttpServletRequest request) throws BaseAppException{
TinsureSchemeOrder schemeOrder = getSchemeOrderInfo(orderId);
String fileNames = schemeOrder.getPolicyFilePath();
String fileName = fileNames.substring( fileNames.length()-26);
String suffix = fileName.substring(fileName.indexOf(".")+1, fileName.length());
String remotePath = ConfigConst.FTP_REMOTEPATH +BaseConst.WEBNAME + "/" + BaseConst.INSURE + "/"+orderId+"/";
ServletOutputStream output = null;
InputStream input = null;
try {
byte[] buffer = JschFtpUtil.get(ConfigConst.INNER_FTP_REMOTEHOST,
ConfigConst.INNER_FTP_PORT, remotePath, fileName,
ConfigConst.INNER_FTP_USER, ConfigConst.INNER_FTP_PASSWORD);
if (buffer.length == 0) {
throw new Exception("从FTP获取对账文件失败:"+fileName);
}
input = new ByteArrayInputStream(buffer);
output = response.getOutputStream();
if("pdf".equals(suffix)){
response.reset();
response.setContentType("application/pdf");
}else if("jpg".equals(suffix)){
response.reset();
response.setContentType("image/jpeg");
}
response.setHeader("Content-disposition", "inline;attachment;filename=" + CommonUtil.encodeFileName("保单详情"+fileName, request));
byte imageArray[] = new byte[4064];
int len = 0;
while((len = input.read(imageArray)) != -1){
output.write(imageArray, 0, len);
}
output.flush();
} catch (IOException e) {
logger.info(e.getMessage());
throw new BaseAppException("读取文件失败");
}catch(Exception e){
logger.info(e.getMessage());
throw new BaseAppException(e.getMessage());
}finally{
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Controller 类
@RequestMapping("/previewPolicy")
public void previewPolicy(String orderId,HttpServletResponse response,HttpServletRequest request) throws BaseAppException{
insureSchemeOrderTxService.previewPolicyFile(orderId, response, request);
}