0

我正在尝试将一个文件 PDF 文件上传到服务器。为此,我需要将 PDF 文件转换为 BASE64 字符串。

转换正在发生,但是当我尝试将 Base64 转换为 PDF 时,它没有提供适当的价值。我收到如下图所示的错误。

Android代码, 文件选择代码

@SuppressLint("NewApi")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult( requestCode, resultCode, data );

    if (requestCode == PDF_REQ_CODE && resultCode == RESULT_OK && data != null && data.getData() != null) {
        uri = data.getData();
        //String path=data.getData().getPath();
        btnPdfFileChooser.setText( "PDF is Selected" );
        //Toast.makeText(FileUploadActivity.this, uri.toString(), Toast.LENGTH_SHORT).show();
        //InputStream inputStream = c.getContentResolver().openInputStream(path)
        PdfUploadFunction();
    }
}

上传功能(需要编写API调用来更新服务器中的详细信息。它现在正在等待。)

private void PdfUploadFunction() {
    // Getting pdf name from EditText.
    PdfNameHolder = strPdfFileName.toString().trim();
    // Getting file path using Filepath class.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        PdfPathHolder = FilePath.getPath( this, uri );
    }
    // If file path object is null then showing toast message to move file into internal storage.
    if (PdfPathHolder == null) {
        Toast.makeText( this, "Please move your PDF file to internal storage & try again.", Toast.LENGTH_LONG ).show();
    }
    // If file path is not null then PDF uploading file process will starts.
    else {
        String base64 = getBase64FromPath( PdfPathHolder );
        //String base64 = encodeFileToBase64Binary( PdfPathHolder );
        Toast.makeText( this, "base64-" + base64, Toast.LENGTH_LONG ).show();
        Log.e( "base64-", base64.toString() );
    }
}

BASE64 转换代码。

 public static String getBase64FromPath(String path) {
      
        byte[] byteArray = null;
        try {
            File file = new File( path );
            InputStream inputStream = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024 * 11];
            int bytesRead = 0;

            while ((bytesRead = inputStream.read(b)) != -1) {
                bos.write(b, 0, bytesRead);
            }

            byteArray = bos.toByteArray();

            Log.e("Byte array", ">" + byteArray);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.encodeToString(byteArray, Base64.NO_WRAP);
    }

我用谷歌搜索了很多。但我无法为此找到任何正确的解决方案。希望有人能提供帮助。

在此处输入图像描述

4

0 回答 0