Question

I use guava and apache commons to convert temporary image that have been loaded from the server but the conversion result is a corrupted file. the problem that "sampleFile" is corrupted and I don't know why until I have no error.

import com.google.common.io.Files;
import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;


public class imageDecoder {


    public static void main(String[] args) {
        byte[] data = null;
        final File input = new File("C:\\Users\\xxx\\AppData\\Local\\Temp\\multipartBody2180016028702918119asTemporaryFile");
        try {
            data = Base64.decodeBase64(Files.toByteArray(input));
        } catch (Exception ex) {
                System.out.print("problem");
        }
        final File f = new File(String.format("sampleFile_%s.jpg", UUID.randomUUID()));

        try {
            if (!f.exists())
                f.createNewFile();
            final FileOutputStream fos = new FileOutputStream(f);
            fos.write(data);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            System.out.print("file not found");
        } catch (IOException e) {
            System.out.print("exception");
        }
    }
}
Was it helpful?

Solution

Based on your comment, it sounds like the the original file (input) contains the actual bytes of the image. But for some reason, you're then reading those bytes in as if they are the Base 64 encoded ASCII representation of the image. Clearly they aren't, so why are you doing this? If you skip the Base64.decodeBase64 step, I'm guessing things will work as expected.

Of course, in that case what you're doing is simply copying the bytes of input to f, which is simpler and more efficient to do as:

Files.copy(input, f);

Or if you have no need to leave the temporary file where it is, moving the file is even better:

Files.move(input, f);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top