希望能帮到大家,有疑问联系
package com.qb.modules.organtrans.interactive.jinshang
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.Date
import java.util.List
import java.util.Properties
import org.apache.commons.io.FileUtils
import org.apache.commons.io.FilenameUtils
import org.apache.commons.io.IOUtils
import org.apache.commons.lang3.StringUtils
import org.apache.tools.ant.taskdefs.Copyfile
import org.drools.io.impl.ClassPathResource
import org.drools.lang.DRLExpressions.neg_operator_key_return
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.support.ClassPathXmlApplicationContext
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import com.jcraft.jsch.ChannelSftp
import com.qb.modules.organtrans.attachment.dto.AttachmentDTO
import com.qb.modules.organtrans.attachment.service.AttachmentService
import com.qb.modules.organtrans.common.Constants
import com.qb.modules.organtrans.orgpackconfig.service.OrgPackConfigService
import com.qb.modules.organtrans.util.FileUtil
import com.qb.modules.organtrans.util.SFTPUtils
import com.qb.modules.util.CommonUtil
import com.qb.modules.util.ConfigUtil
import com.qb.modules.util.ZipCompress
import com.qb.platform.core.fastdfs.task.SynSingleFileDownloadWorker
import com.qb.platform.core.fastdfs.task.SynSingleFileUploadWorker
import com.qb.platform.tools.common.DateUtil
import net.sf.ehcache.hibernate.ccs.EhcacheNonstrictReadWriteCache
@Service
public class SftpOperateUtils {
private static final Logger logger = LoggerFactory.getLogger(SftpOperateUtils.class)
@Autowired
OrgPackConfigService orgPackConfigService
@Autowired
AttachmentService attachmentService
@Autowired
SynSingleFileDownloadWorker synSingleFileDownloadWorker
@Autowired
SynSingleFileUploadWorker synSingleFileUploadWorker
//上传文件--贷款申请阶段上传影像
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "/spring-base.xml", "/spring-shiro.xml" })
SftpOperateUtils sftpOperateUtils = context.getBean(SftpOperateUtils.class)
try {
//boolean uploadSignContract = sftpOperateUtils.uploadSignContract("564564",220L, "5,12cba975f00e05","QT1",3L,"fsdf.jpg")
sftpOperateUtils.js_downLoadConract("2017091200001801", "2017091200001801", 1L, "QT15", 5L)
//boolean b = fillMaterial("123456","12365411",1L,2L,"03","QT15")
//boolean b = sftpOperateUtils.fillMaterial("104788","2017123456", 1L, 2L, "03", "QT15")
} catch (Exception e) {
e.printStackTrace()
}
}
public boolean fillMaterial(String appsleqid, MultipartFile[] attachmets, Long listId, Long listType,String node,String fileTypeCode) throws Exception {
boolean isOK = false
File endfile = null
String filepath = null
String filename = null
//获取sftp上传路径
String local = ConfigUtil.getConfig(Constants.DirPath.COMMON_TEMP)+File.separator+appsleqid
endfile = new File(local)
if(!endfile.exists() && !endfile.isDirectory()){
//endfile.mkdir()
endfile.mkdirs()
}
String dellocal = ConfigUtil.getConfig(Constants.DirPath.COMMON_TEMP)
//创建文件夹
String sftpPath = CommonUtil.getPropertiesValue("sftp.properties", "jinshang.fillmaterial")+"/"+appsleqid
OutputStream outputStream= null
SFTPUtils sftputils = new SFTPUtils()
//获取晋商sftp服务器信息
SFTPUtils sftp1 = getSftp()
ChannelSftp sftp = sftp1.getSFTPClient()
try {
if (node.equals("03")) {//补全影像资料
for (MultipartFile multipartFile : attachmets) {
filename = multipartFile.getOriginalFilename()
File file = new File(filename)
String path = file.getAbsolutePath()
multipartFile.transferTo(file)
File startfile = new File(path)
filepath = synSingleFileUploadWorker.uploadSeaweed(file)
//2 入attachment表
AttachmentDTO attachmentDTO
attachmentDTO= new AttachmentDTO()
attachmentDTO.setListId(listId)
attachmentDTO.setListType(listType)
attachmentDTO.setFileName(filename)
attachmentDTO.setCreateDate(new Date())
attachmentDTO.setFileTypeCode(fileTypeCode)
attachmentDTO.setFilePath(filepath)
attachmentService.insertAttachment(attachmentDTO)
//移动到临时目录并打包
startfile.renameTo(new File(local+"\\"+startfile.getName()))
}
//压缩
String zipoutpath = local+".zip"
ZipCompress.zipFiles(new File(local).listFiles(), new File(zipoutpath))
//创建文件夹
sftputils.mkDir(sftpPath, sftp)
//上传
sftp.put(zipoutpath,sftpPath)
//删除本地文件
delFolder(dellocal)
isOK=true
}
} catch (Exception e) {
isOK =false
e.printStackTrace()
logger.error("执行方法fillMaterial异常:", e)
} finally {
outputStream.flush()
outputStream.close()
sftp.disconnect()
}
return isOK
}
//(respon.getApplseqcontractid(),info.getIouSupportDTO().getBusiUuid(),info.getId(),"QT14",FileUtil.TYPE_CONTRACT_FILE)
public String js_downLoadConract(String path, String applseq, Long listId, String fileTypeCode,
Long listType) throws Exception {
String filepath = null
String destt = null
SFTPUtils sftp = getSftp()
//获取合同下载路径
String sftpDir = CommonUtil.getPropertiesValue("sftp.properties", "jinshang.supply.upload")+path
//创建本地文件夹
String dellocal = ConfigUtil.getConfig(Constants.DirPath.COMMON_TEMP)
String directoryPath = ConfigUtil.getConfig(Constants.DirPath.COMMON_TEMP)+ File.separator + applseq
File dirPath = new File(directoryPath)
if (!dirPath.exists() && !dirPath.isDirectory()) {
dirPath.mkdirs()
}
String filename = applseq+".zip"
String localfile = directoryPath +File.separator + filename
String sftpfile = sftpDir+"/"+filename
try {
if (sftp.isFileExist(filename,sftpDir)) {//如果当前路径,存在以这个流水号命名的文件
logger.error("从SFTP下载文开始,js_"
+ "LoadConract-sftp.get(sftpFile, localFile)-start:" + applseq)
sftp.get(sftpfile, localfile)
logger.error("从SFTP下载文结束,js_downLoadConract-sftp.get(sftpFile, localFile)-end:" + applseq)
}
} catch (Exception e) {
logger.error("文件解析失败,js_downLoadConract-sftp-error:" + applseq + "," + e.getMessage())
e.printStackTrace()
}finally {
try {
sftp.disconnect()
} catch (Exception e) {
logger.error("关闭SFTP连接时异常,js_downLoadConract-error," + e.getMessage())
e.printStackTrace()
}
}
//解压缩合同
String dest = directoryPath+File.separator+applseq
ZipCompress.unZip(localfile, dest, true)
File file = new File(localfile)
file.delete()
File file2 = new File(directoryPath)
if (file2.isDirectory()) {
String[] filelist = file2.list()
for (int i = 0
destt = directoryPath + "\\" + filelist[i]
}
}
//2 入attachment表
try {
filepath = synSingleFileUploadWorker.uploadSeaweed( new File(destt) )
AttachmentDTO attachmentDTO
attachmentDTO= new AttachmentDTO()
attachmentDTO.setListId(listId)
attachmentDTO.setListType(listType)
attachmentDTO.setFileName(filename)
attachmentDTO.setCreateDate(new Date())
attachmentDTO.setFileTypeCode(fileTypeCode)
attachmentDTO.setFilePath(filepath)
attachmentService.insertAttachment(attachmentDTO)
//删除本地文件
delFolder(dellocal)
} catch (IOException e) {
logger.error("入attachment表异常,js_downLoadConract-error," + e.getMessage())
e.printStackTrace()
}
return filepath
}
//胡文使用,下载并上传
public boolean download(String id,String appsleqid ,String coorgId){
//创建本地路径
boolean isOk=false
String localpath = ConfigUtil.getConfig(Constants.DirPath.COMMON_TEMP)+File.separator+appsleqid
String dellocal = ConfigUtil.getConfig(Constants.DirPath.COMMON_TEMP)
File localdir = new File( localpath )
//创建文件夹
if(!localdir.exists() && !localdir.isDirectory()){
localdir.mkdir()
}
try {
List orgPackConfigList=orgPackConfigService.selectOrgPackByCoOrgID(Long.valueOf( coorgId),Constants.TemplateType.CONTRACT_EXCEL)
//查
List attachmentDTOs = attachmentService.searchAttachemnt(id,FileUtil.TYPE_CONTRACT_FILE,orgPackConfigList)
//写
for (AttachmentDTO attachmentDTO : attachmentDTOs) {
String fileExt = FilenameUtils.getExtension(attachmentDTO.getFileName())
String attachmentFilePath = localpath + System.getProperty("file.separator")+"/"+appsleqid+"."+fileExt
String attachmentFilePath1 = localpath +File.separator+appsleqid+"."+fileExt
File attachmentFile = new File( attachmentFilePath )
String fileName = attachmentDTO.getFileName()
FileUtils.writeByteArrayToFile(attachmentFile, synSingleFileDownloadWorker.downloadSeaweed( attachmentDTO.getFilePath()))
}
String zipoutpath = localpath+".zip"
ZipCompress.zipFiles(localdir.listFiles(), new File(zipoutpath))
String sftpPath = CommonUtil.getPropertiesValue("sftp.properties", "jinshang.sign")+"/"+appsleqid
SFTPUtils sftp1 = getSftp()
ChannelSftp sftp = sftp1.getSFTPClient()
SFTPUtils sftputils = new SFTPUtils()
sftputils.mkDir(sftpPath, sftp)
sftp.put(zipoutpath,sftpPath)
sftp.disconnect()
//删除本地文件
delFolder(dellocal)
isOk=true
} catch (Exception e) {
isOk=false
logger.error("执行方法download异常:", e)
}finally {
}
return isOk
}
public boolean uploadSignContract(String busiUuid, Long listId, String downPath, String fileTypeCode,
long listType,String fileName,String remark) {
SFTPUtils utils = null
String sftpPath = CommonUtil.getPropertiesValue("sftp.properties", "jinshang.sign.contract.upload")+File.separator + busiUuid
boolean isOk = false
String tempPath=""
try {
// 入库 上传到晋商sftp
if (StringUtils.isNotBlank(downPath)) {
byte[] contractFile = synSingleFileDownloadWorker.downloadSeaweed(downPath)
utils = getSftp()
tempPath = ConfigUtil.getConfig(Constants.DirPath.COMMON_TEMP) + File.separator
+ DateUtil.getDateToStringSS(new Date())
File file = new File(tempPath)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs()
}
String filePathAll=tempPath+File.separator+fileName
File f=new File(filePathAll)
//压缩
FileUtils.writeByteArrayToFile(f, contractFile)
File f2 = new File(tempPath)
String zipfile = busiUuid+".zip"
File zipoutfile = new File(zipfile)
ZipCompress.zipFiles(f2.listFiles(), zipoutfile)
utils.upload(sftpPath,zipfile)
AttachmentDTO dto = new AttachmentDTO()
dto.setListId(listId)
dto.setFileTypeCode(fileTypeCode)
dto.setFilePath(downPath)
dto.setListType(listType)
dto.setFileName(fileName+File.separator+fileName)
dto.setCreateDate(new Date())
dto.setRemark(remark)
attachmentService.insertAttachment(dto)
isOk = true
f.delete()
FileUtils.deleteDirectory(file)
}
} catch (Exception e) {
isOk = false
logger.error("uploadSignContract 上传签完章的合同报错", e)
} finally {
if (utils != null) {
try {
utils.disconnect()
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
return isOk
}
//获取晋商sftp参数
private static SFTPUtils getSftp() {
Properties prop = new Properties()
ClassPathResource cp = new ClassPathResource("sftp.properties")
try {
prop.load(cp.getInputStream())
} catch (IOException e) {
e.printStackTrace()
}
String host = prop.getProperty("jinshang.host").trim()
int port = Integer.parseInt(prop.getProperty("jinshang.port").trim())
String username = prop.getProperty("jinshang.username").trim()
String password = prop.getProperty("jinshang.password").trim()
return new SFTPUtils(host, port, username, password)
}
private void delFolder(String dellocal) {
try {
delAllFile(dellocal)
String filePath = dellocal
filePath = filePath.toString()
java.io.File myFilePath = new java.io.File(filePath)
myFilePath.delete()
}
catch (Exception e) {
System.out.println("删除文件夹操作出错")
e.printStackTrace()
}
}
private void delAllFile(String dellocal) {
File file = new File(dellocal)
if (!file.exists()) {
return
}
if (!file.isDirectory()) {
return
}
String[] tempList = file.list()
File temp = null
for (int i = 0
if (dellocal.endsWith(File.separator)) {
temp = new File(dellocal + tempList[i])
}
else {
temp = new File(dellocal + File.separator + tempList[i])
}
if (temp.isFile()) {
temp.delete()
}
if (temp.isDirectory()) {
delAllFile(dellocal+"/"+ tempList[i])
delFolder(dellocal+"/"+ tempList[i])
}
}
}
}