在Java Struts web应用程序中使用JSch进行文件上传时遭到破坏



上传文件时,我没有收到任何异常,但文件由于损坏而无法打开。

我们在应用程序中使用Struts1.x。

我认为输入流会出现一些问题。它只读取文本文件。

如果我上传pdf或xls文件,它不会打开,显示消息"文件损坏或扩展名更改"。

有人能告诉我解决办法吗?

从操作类上传方法:

public static void uploadFiles(FormFile[] formFile, FilesVO fVO) 
throws BaseException {
Logger logger = LogManager.getLogger();
boolean isSaved = false;
int port=ATAConstants.SERVER_PORT;
FileStorageVO fsVO = null;
try {            
if ( ( null != formFile[0].getFileName()
&& !formFile[0].getFileName().trim().equalsIgnoreCase(""))
|| ( null != formFile[1].getFileName()
&& !formFile[1].getFileName().trim().equalsIgnoreCase(""))
|| ( null != formFile[2].getFileName()
&& !formFile[2].getFileName().trim().equalsIgnoreCase(""))
) {
fsVO = SFTPFileManager.getFileStorageDetails(SFTPFileManager.FILE_CATEGORY_WORKORDER);                
JSch jsch = new JSch();
Session session = null;
session = jsch.getSession(fsVO.getSAccountName(),fsVO.getSFTPHostName(),port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(fsVO.getSPassword());
session.connect();
ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
sftp.connect();
if (sftp.isConnected()==true) {
for (int i = 0; i < formFile.length; i++) {
if (null!=formFile[i] && null != formFile[i].getFileName()
&& !formFile[i].getFileName().trim().equalsIgnoreCase("")) {
int iFileCount = CommonDAO.getFileCount().intValue();
String sActualFileName = formFile[i].getFileName();
String sDestinationStorageFileName =
SFTPFileManager.getStorageFileName(
fVO.getSFileCategory(),
fVO.getEntityId(),
iFileCount++,
sActualFileName);
isSaved =SFTPFileManager.uploadFile(sftp,
fsVO.getSFilePath(),
formFile[i],
sDestinationStorageFileName);            
fVO.setActualFileName(sActualFileName);
fVO.setStorageFileName(sDestinationStorageFileName);
fVO.setStorageId(ATAConstants.STORAGE_ID_WORKORDER);
if (isSaved) {
CommonDAO.addFiles(fVO);
}
}
}
}
sftp.exit();
sftp.disconnect();
}
}catch (JSchException   e) {
logger.error("Error while uploading the file", e);
throw new BaseException(e, "Exception occured while uploading file");
}catch (SftpException e) {
logger.error("Error while uploading the file", e);
throw new BaseException(e, "Exception occured while uploading file");
} catch (IOException e) {
logger.error("Error while uploading the file", e);
throw new BaseException (e, "Exception occured while uploading file");
}  
}

这是使用通道sftp的文件上传方法sftpFileManager.java

public static boolean uploadFile(ChannelSftp sftp, String sDestinationFolder,
FormFile fUploadFile, String sDestinationStorageFileName)
throws IOException, FileNotFoundException, SftpException {
boolean isSaved = false;
sftp.cd(sDestinationFolder);`enter code here`
InputStream is = fUploadFile.getInputStream();
if(is.read()!=-1){
sftp.put(is, sDestinationStorageFileName);
isSaved = true;
}
is.close();    
return isSaved;
}
if(is.read()!=-1){

上面读取并丢弃上传文件中的第一个字节。所以FTP上传从第二个字节开始。删除该代码。

最新更新