首页 > 解决方案 > 上传Pdf文件未在android中转换为base64

问题描述

我无法将 pdf 文件转换为 base64 字符串,但是当我打开 pdf 文件时文件上传成功,它显示 0kb 文件大小。相同的代码适用于图像,但是当我尝试用于转换为 pdf 文件时,它不起作用。在我的代码中,我创建了一个名为“NewBase64”的方法,我正在将 pdf 文件转换为 base64,任何人都可以告诉我哪里出错了,请帮助我。

private String KEY_IMAGE = "image";
            private String KEY_NAME = "name";

            private int PICK_IMAGE_REQUEST = 1;
            VolleyAppController volleyAppController;
            mydb db;
            public static String url = "http://xxx.xxx.x.x:xx/Android_Service.asmx/UploadPDFFile";
            int SELECT_MAGAZINE_FILE = 1;
            private File myFile;
            String encodeFileToBase64Binary = "";


            private String NewBase64(String Path) {

                String encoded = "";
                try {
                    File file = new File(Path);

                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(bos);
                    oos = new ObjectOutputStream(bos);
                    oos.writeObject(file);
                    bos.close();
                    oos.close();
                    byte[] bytearray = bos.toByteArray();
                    encoded = Base64.encodeToString(bytearray, Base64.DEFAULT);
                } catch (Exception ex) {

                }
                return encoded;
            }


            private void uploadImage() {


                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {

                        String image = null;


                        image = NewBase64(encodeFileToBase64Binary);



                        String name1 = name.getText().toString().trim();


                        Map<String, String> params = new Hashtable<String, String>();


                        params.put(KEY_IMAGE, image);
                        params.put(KEY_NAME, name1);


                        return params;
                    }
                };

        }     

标签: javaandroidandroid-volley

解决方案


您可以使用以下方法将 PDF 转换为 base64

public String NewBase64(File mfile) {
        ByteArrayOutputStream output = null;
        try {
            InputStream inputStream = null;
            inputStream = new FileInputStream(mfile.getAbsolutePath());
            byte[] buffer = new byte[8192];
            int bytesRead;
            output = new ByteArrayOutputStream();
            Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                output64.write(buffer, 0, bytesRead);
            }
            output64.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return output.toString();
    }

推荐阅读