Search code examples
javaftpapache-commons-net

File gets a full path of local source file as its name when uploaded using Java FTPClient


So i have a basic GUI application, where there is an option to upload image files to an ftp server. Everything works fine except one thing: the files are getting renamed during the upload. The new name of the file will be the full path of the directory, which contained the file.

So in my case, i have an image on the desktop: C:\Users\Bob\Desktop\image.png. When I select the file in the JfileChooser, the name is still just image.png. But when I click upload to FTP server, the file will be renamed to C:\Users\Bob\Desktop\image.png. So if I want to download that file, I have to use this path: /home/user/users/xy/images/C:\Users\Bob\Desktop\image.png in order to download it. Idk what causing this problem. I use FTPClient.putFileToPath(file,path) to upload the files, and it works fine, the files will be uploaded. I tried to copy a file from my machine to the ftp server with total commander, and this problem never occurred. I provided some code snippet, which does the uploading job.

uploadmenu.getUploadBtn().addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if(!uploadMenuValidate()){
           for(File f : img_container){
            try {
                //This still gives me the normal file name
                System.out.println(f.getName()); 
                
                ftp.putFileToPath(f, FtpClient.DEST_DIR+SQLData.APP_USERNAME+"/"+f);

                 
            } catch (IOException ex) {
                ex.printStackTrace();
                }
            }
           popup.setVisible(false);
        }
    }
});

I have all the files in the img_container array that I selected in the JFileChooser.


Solution

  • The File.toString() returns:

    Returns the pathname string of this abstract pathname

    You want to use File.getName():

    ftp.putFileToPath(f, FtpClient.DEST_DIR+SQLData.APP_USERNAME+"/"+f.getName());