简体   繁体   中英

Encode/decode Base64 fails

in my application client-server, on client side I send the file content in following format:

public static String getImageFromURI (Context contesto, Uri uri) {
    InputStream is;
    ByteArrayOutputStream bos;
    try {
        is = contesto.getContentResolver().openInputStream(uri);
        bos = new ByteArrayOutputStream();

        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = is.read(buf)) != -1;) {
                bos.write(buf, 0, readNum); //no doubt here is 0
            }
        } catch (IOException ex) {
            Log.d("TAG_F2S", "Sono nel catch IOExcetion con emssage = " + ex.getMessage());
            ex.printStackTrace();
            return null;
        }

        return new String (Base64.encode(bos.toByteArray(), Base64.DEFAULT), "UTF-8");
    } catch (FileNotFoundException fnfe) {
        Log.d("TAG_F2S", "Sono nel catch FileNotFoundExcetion con emssage = " + fnfe.getMessage());
        fnfe.printStackTrace();

        return null;
    } catch (UnsupportedEncodingException uee) {
        Log.d("TAG_F2S", "Sono nel catch UnsupportedEncodingExcetion con emssage = " + uee.getMessage());
        uee.printStackTrace();

        return null;
    }
}

and on server side I try to create the file as follow:

byte [] byteFile = java.util.Base64.getDecoder ().decode(contenuto.getBytes("UTF-8"));

Files.write(Paths.get(myPath), byteFile);

But I can't obtain the result cause the exception like this:

java.lang.IllegalArgumentException: Illegal base64 character a
at java.util.Base64$Decoder.decode0(Unknown Source)
at java.util.Base64$Decoder.decode(Unknown Source)
....

What's my error? I don't understand.. Thanks for your help.


EDIT: The String that i send to the server is the following: https://codeshare.io/GqQWNA

I found the problem:

when I encode the file content and I send data to the server in POST request, the content is modified replacing alland only '+' characters with ' ' (whitespace). Operating the following action on server side:

java.util.Base64.getMimeDecoder().decode(contenuto.replace(" ", "+"));

I don't have the problem. Note that i used getMimeDecoder and not getDecoder , otherwise it doesn't work.

Does anyone know the reason for this problem?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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