Zip file getting corrupted when uploaded to server

2019-05-26 23:11发布

问题:

My java program uploads a zip file from my system to FTP server. uploadfile() is a function that contains the uploading code.

uploadfile("192.168.0.210","muruganp","vm4snk","/home/Admin/GATE521/LN_RB_Semivalid2junk/Output/"+date+"_RB1.zip","/fileserver/filesbackup/Emac/"+date+"_RB1.zip");

public static boolean uploadfile(String server, String username,
        String Password, String source_file_path, String dest_dir) {
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        ftp.connect(server);
        ftp.login(username, Password);
        System.out.println("Connected to " + server + ".");
        System.out.print(ftp.getReplyString());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            return false;
        }
        System.out.println("FTP server connected.");
        InputStream input = new FileInputStream(source_file_path);
        ftp.storeFile(dest_dir, input);
        System.out.println(ftp.getReplyString());
        input.close();
        ftp.logout();
    } catch (Exception e) {
        System.out.println("err");
        e.printStackTrace();
        return false;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (Exception ioe) {}
        }
    }
    return true;
}

The zip file that I do have in my system is perfect. But after uploading the same in the server location,downloading the same, and extracting the problem occurs. "The file is corrupt" says the error. What should I do to resolve this issue. Kindly advise on this.

I suspect the problem would be something like, transferring through ASCII mode. It should actually be transferred through binary mode as per this QUESTION. How to attain the same? Please advise.

回答1:

Best guess is that the FTP upload is using ascii mode which will corrupt a binary file like a zip. Verify this and if so change it to binary mode instead.



回答2:

Use the setFileType method of FTPClient to set it to FTP.BINARY_FILE_TYPE before uploading



回答3:

I just used setFileType(FTP.BINARY_FILE_TYPE) to solve it. Those information are really helpful! Thanks a lot.