FTPClient - Java, upload file

做~自己de王妃 提交于 2019-11-28 06:50:26
An̲̳̳drew

It doesn't work because the default transfer mode for FTPClient is FTP.ASCII_FILE_TYPE. You just need to update the configuration to transfer in binary mode.

Stevan Buzejic

Add this to your file

ftp.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);

I had the same problem with xlsx files and this was a good solution.

It's often forgotten that FTP has two modes of operation - one for text files and the other for binary (image) files. In the good old days, connecting from a command line ftp client, we'd carefully remember to set the transfer mode before requesting a file - or we'd run into exactly the sort of problem you seem to be having. Today a lot of situations seem to default to binary, but not apparently yours.

You probably need to tell your ftp implementation to transfer in binary/image mode.

Try to use BufferedInputStream, this is a (working) code sample:

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
res = client.storeFile("File Name", bis);
bis.close();
client.logout();

From documentation

This method does NOT close the given InputStream.

So close the FileInputStream before calling logout()

Try this.

objFtpClient.setFileType(FTP.BINARY_FILE_TYPE);

objFtpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);

objFtpClient.enterLocalPassiveMode();

For Me only ftp.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE) worked, while when I was using ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE) File was getting corrupt.

This looks like a bug in the Commons NET library, which affected version 3.0. Try a newer version (3.0.1), which fixed the bug.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!