简体   繁体   English

Java:上传文件到FTP问题(丢包)

[英]Java: upload file to FTP problem (packets lost)

I'm trying to transfer a file from my Java application to an FTP server the program works, the file is transferred, but when I go to open in the FTO folder, the file is corrupted, I think that packets are lost during the file transfer. 我正在尝试将文件从我的Java应用程序传输到FTP服务器程序正常工作,文件被传输,但是当我在FTO文件夹中打开时,文件已损坏,我认为文件在文件丢失期间丢失传递。 Why? 为什么? And how can I fix this? 我该如何解决这个问题?

Another question, how can I stop the while if I want to stop the file upload? 还有一个问题,我怎么可以停止while如果我想阻止文件上传?

Thanks everybody! 谢谢大家!

The code inside my class: 我班里的代码:

FTPClient client = new FTPClient();
InputStream is = null;
//...
try{
 client.connect(MY_FTP_URL);
 client.login(USER, PASS);
 InputStream is = new FileInputStream(file_path);
 OutputStream os = client.storeFileStream(file_name);
 byte[] buffer = new byte[1024];
 int len;
 //I use this way to check the transfer progress
 while((len = is.read(buffer)) != -1){
  os.write(buffer, 0, len);
  os.flush();
 }
 os.close();
} catch (IOException e){
 e.printStackTrace();
} finally{
 try{
  if(is != null){
   is.close();
  }
  client.disconnect();
 } catch(IOException e){
  e.printStackTrace();
 }
}

Check out the FAQ : 查看常见问题解答

Q: Why are my files corrupt after transfer? 问:为什么我的文件在转移后损坏了?

A: The most common cause for this is when the file is transfered as ASCII but the contents of the file are not ASCII and the file should be transferred as BINARY. 答:最常见的原因是当文件以ASCII格式传输但文件内容不是ASCII时,文件应作为BINARY传输。 RFC 959 says the default transfer mode should be ASCII. RFC 959表示默认传输模式应为ASCII。 FTPClient conforms to the standard. FTPClient符合标准。 You must explicitly call setFileType(FTP.BINARY_FILE_TYPE); 您必须显式调用setFileType(FTP.BINARY_FILE_TYPE); to request binary transfer mode after logging in to the FTP server. 登录FTP服务器后请求二进制传输模式。

Call setFileType(FTP.BINARY_FILE_TYPE); 调用setFileType(FTP.BINARY_FILE_TYPE);

FTP has two modes ASCII (typically the default) and binary. FTP有两种模式ASCII(通常是默认值)和二进制模式。 If you are transferring anything other then text you must set the client into binary mode. 如果要传输除文本之外的任何内容,则必须将客户端设置为二进制模式。

How to set the mode varies on the FTP client implementation, but for Commons IO see http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html#setFileType(int ) 如何设置模式因FTP客户端实现而异,但对于Commons IO,请参阅http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html#setFileType(int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM