将PDF文件上传到服务器编码为base64字符串,在Android

时间:2016-08-19 16:08:45

标签: android pdf encoding compression android-volley

我正在开发一款Android应用。在我的应用程序中,我需要将PDF文件上传到服务器。我正在使用Volley与服务器进行交互。但我在将pdf文件上传到服务器时遇到问题。我知道如何将图像压缩上传到字符串中。但对于PDF,它有问题。

我将选择的pdf文件转换为活动结果中的base64编码字符串

            if(requestCode==SELECT_BOOK)
            {
                Uri bookUri = data.getData();
                if(bookUri!=null)
                {
                    String filePath = bookUri.toString();
                    String mime = app.getMimeType(filePath);
                    if(mime!=null && !mime.isEmpty() && (mime.toLowerCase()=="application/pdf" || mime.toLowerCase()=="application/txt" || mime.toLowerCase()=="application/text"))
                    {
                        try{
                            InputStream iStream =   getContentResolver().openInputStream(bookUri);
                            byte[] byteArray = app.getBytes(iStream);
                            bookFileCompressedString = app.encodeByteArrayIntoBase64String(byteArray);
                            ivBookFile.setImageResource(R.drawable.book_selected);
                        }
                        catch (IOException e)
                        {
                            Toast.makeText(getBaseContext(),"An error occurred with file chosen",Toast.LENGTH_SHORT).show();
                        }
                        if(mime.toLowerCase()=="application/pdf")
                        {
                            bookFileExtension = "pdf";
                        }
                        else{
                            bookFileExtension = "txt";
                        }
                    }
                    else{
                        Toast.makeText(getBaseContext(),"Unable to process file you have chosen.",Toast.LENGTH_SHORT).show();
                    }
                }
            }

这些是app实例中的方法(也是Base64编码方法)

 public byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }

    public static String encodeByteArrayIntoBase64String(byte[] bytes)
    {
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

然后我使用这样的凌空发布到服务器

param.put("image_file",imageCompressedString);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, param, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    closeFixedMortalLoading();
                    Toast.makeText(getApplicationContext(),"Book successfully contributed. Thank you.",Toast.LENGTH_SHORT).show();
                    finish();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    closeFixedMortalLoading();
                    String errorMessages = AppSingleton.ParseVolleyErrorMessageToString(error);
                    if(errorMessages!=null && !errorMessages.isEmpty())
                    {
                        try{
                            JSONObject jsonError = new JSONObject(errorMessages);
                            showServerErrors(jsonError);
                        }
                        catch (JSONException e)
                        {
                            Toast.makeText(getBaseContext(),"Error in parsing data from server",Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }){
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String,String> headers = new HashMap<>();
                    headers.put(AppSingleton.API_KEY_FIELD,AppSingleton.API_KEY);
                    headers.put(AppSingleton.AUTH_TOKEN_FIELD,app.getAuthToken());
                    return headers;
                }
            };
            VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(request);

如您所见,我通过了编码字符串。但是Volley请求只是继续发送到服务器并且永远不会结束。也没有达到错误监听器。那可能是因为压缩文件的数据太大了。所以我记录压缩的字符串。

这就是我得到的

enter image description here

正如您所看到的,即使我只记录下一次,也会在logcat中显示许多行。

Log.i("COMPRESSED_STRING",bookFileCompressedString);

所以我认为凌空无法发送到服务器,因为数据太大了。编码pdf文件的平均结果太大。这就是为什么即使日志显示多行。如何使用Volley压缩和上传pdf文件到服务器?

0 个答案:

没有答案