简体   繁体   English

如何使用FTPClient从FTP下载图像?

[英]How to Download an image from FTP using FTPClient?

I m using this code and try to download an png pic from server .this is code 我正在使用此代码并尝试从服务器下载一个png图片。这是代码

import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import org.apache.commons.net.ftp.FTPClient;
public class NetTest {
  public static void main(String[] args){
    FTPClient client = new FTPClient( );
    OutputStream outStream;
    try {

      client.connect( "server" );
      client.login("noman@mindzone.co.in", "pass");

      String remoteFile = "Pages/page0001.png";
      outStream = new FileOutputStream( "C:\\asd.png" );
      client.retrieveFile(remoteFile, outStream);

    } catch(IOException ioe) {
      ioe.printStackTrace();
      System.out.println( "Error communicating with FTP server." );
    } finally {
      try {
        client.disconnect( );
      } catch (IOException e) {
        System.out.println( "Problem disconnecting from FTP server" );
      }
    }

  }
}

this code gives me no error but when i open the image it shows me invalid image . 这段代码没有给我任何错误但是当我打开图像时它会显示无效图像。

You got corrupted image because the FTPClient uses TEXT_FILE_TYPE by default. 您的图像已损坏,因为FTPClient默认使用TEXT_FILE_TYPE。 So you have to set file type to binary as follows: 所以你必须将文件类型设置为二进制,如下所示:

client.setFileType(FTP.BINARY_FILE_TYPE);

You have neither flushed the output stream nor closed in finally block. 您既没有刷新输出流也没有在finally块中关闭。 Try that. 试试吧。

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

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