简体   繁体   English

如何将base64转换为不同类型的文件(doc,pdf,word ..etc)?

[英]How to convert base64 to different kind of files ( doc , pdf , word ..etc ) ?

I am working on project where I have to download attachments that i receive from server. 我正在研究必须从服务器接收到的附件的项目。 I have to exploit base64 data and convert it to the appropriate type and download it. 我必须利用base64数据并将其转换为适当的类型并下载。 It works for me perfectly with images ( base 64 => bytes => bitmap ) but I find troubles with other types ( txt , pdf ..etc ) 它对图像非常适合我(基本64 =>字节=>位图),但是我发现其他类型(txt,pdf ..etc)有麻烦

try this 尝试这个

 try {

            File sdcard = Environment.getExternalStorageDirectory();
            File file = new File(sdcard,"test.pdf");

            File new_file_name = new File(sdcard,"new_file.pdf");

            byte[] input_file = IOUtil.readFile(file);


            byte[] encodedBytes = Base64.encode(input_file,URL_SAFE);
            String encodedString = new String(encodedBytes);
            byte[] decodedBytes = Base64.decode(encodedString.getBytes(),URL_SAFE);

            FileOutputStream fos = new FileOutputStream(new_file_name);
            fos.write(decodedBytes);
            fos.flush();
            fos.close();
        }catch (Exception e)
        {
            Log.e("ERROR",e.toString());
        }

And IOUtil class 和IOUtil类

public class IOUtil {

    public static byte[] readFile(String file) throws IOException {
        return readFile(new File(file));
    }

    public static byte[] readFile(File file) throws IOException {
        // Open file
        RandomAccessFile f = new RandomAccessFile(file, "r");
        try {
            // Get and check length
            long longlength = f.length();
            int length = (int) longlength;
            if (length != longlength)
                throw new IOException("File size >= 2 GB");
            // Read file and return data
            byte[] data = new byte[length];
            f.readFully(data);
            return data;
        } finally {
            f.close();
        }
    }
}

this code contain both encode and decode parts 此代码包含编码和解码部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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