Java upload jpg using JakartaFtpWrapper - makes th

2019-02-20 06:17发布

问题:

I've been using JakartaFtpWrapper to upload files from the client Java application to my server (for backup purposes).

The files that are uploaded are text files, png files and jpgs.

I've noticed that the jpg files which are valid on the local machine - somehow become unreadable (corrupt files) on the server (where they were FTPd to). The image file size is similar to the original one, but somehow it is defected.

Here's a code I'm using to write the jpg to the LOCAL disk:

public static void writeJpeg(BufferedImage bfImg, String fileName, float quality) throws IOException{
FileImageOutputStream output = null;
try{
    Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = (ImageWriter)iter.next();
    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(quality);   // an integer between 0 and 1     
    File file = new File(fileName);
    output = new FileImageOutputStream(file);
    writer.setOutput(output);
    IIOImage image = new IIOImage(bfImg, null, null);
    writer.write(null, image, iwp);
}
finally{
    if (output != null){
        output.close();
    }
}

The ftp code is straight forward:

JakartaFtpWrapper ftpClient = new JakartaFtpWrapper();
ftpClient.connectAndLogin(FTP_URL, FTP_USER, FTP_PASSWORD);
ftpClient.setPassiveMode(true);

File[] imageFiles = folder.listFiles()


  for (int j=0; j<imageFiles.length; j++){
        File imageFile = imageFiles[j];
        if (imageFile != null && imageFile.isFile() && (FileUtils.getFileSuffix(imageFile).equals("jpg") || FileUtils.getFileSuffix(imageFile).equals("png"))){ // upload only image files
            ftpClient.uploadFile(imageFile.getAbsolutePath(), imageFile.getName());
        }
    }

Thanks, Ran

回答1:

What's running on the server? Is it an "out of the box" FTP server or something you wrote?

Images are binary data. If JakartaFtpWrapper offers some option of putting the FTP transfer into binary mode, you should do that; I think the most likely cause of your problem is a bad default attempt to process the transfer in text mode. If you compare small images bytewise, you should see Carriage Returns ((char) 0x0d == (char) 13) being added or removed next to 0x0a's. If so, that's your problem.



标签: java ftp jpeg