dongxianchu3541 2017-07-22 14:52
浏览 80

从Android上传图像到PHP的有效方法

I am uploading an image to PHP from Android by converting it to the byte array. After that I simply submit it using POST method.

On server side I do the reverse of what I am doing at client (Android app) side.

I was wondering if there is any other good/efficient/smart way to do this.

Note: I only have to use only PHP/JS/HTML and obviously Java at client side.

  • 写回答

1条回答 默认 最新

  • drdyf42880 2017-07-22 15:38
    关注

    One of the most efficient ways is doing it using Volley, so make sure to include it in your gradle:

    compile 'com.android.volley:volley:1.0.0'
    

    I personally use Universal Image Loader which is included automatically when you include Volley. Since you haven't put any code that you tried, i'll give you some examples. In your activity that you're trying to upload the image, create a button. Add this code when that button is clicked:

    Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    i.setType("image/*");
    startActivityForResult(i, Constants.VALUE_BROWSE_IMAGE_REQUEST);
    

    This will open the gallery in your phone to browse for an image. Declare a variable at the top of your activity:

    private Bitmap mBitmap;
    

    After you choose the image you want to upload from your gallery, write this code:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == Constants.VALUE_BROWSE_IMAGE_REQUEST &&
                resultCode == RESULT_OK &&
                data != null) {
    
            try {
                // Get the photo URI data
                Uri filePath = data.getData();
    
                // Get the Bitmap from Gallery
                mBitmap = decodeBitmap(filePath, this);
            } catch (IOException e) {
                Toast.makeText(this, "Could not open picture.", Toast.LENGTH_SHORT).show();
            }
        }
    }
    

    Now that you have the bitmap of the chosen image, you need to convert that bitmap into base64 string so that Volley can be able to upload it:

    // Before uploading the selected image to the server, we need to convert the Bitmap to String.
    // This method will convert Bitmap to base64 String.
    private String getStringImage(Bitmap bmp) {
        ByteArrayOutputStream b = new ByteArrayOutputStream();
    
        // This part handles the image compression. Keep the image quality
        // at 70-90 so you don't cause lag when loading it on android
        // (0-low quality but fast load, 100-best (original) quality but slow load)
        bmp.compress(Bitmap.CompressFormat.JPEG, 80, b);
        byte[] imageBytes = b.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }
    

    Finally you can start uploading the image:

    private void uploadImage() {
        StringRequest stringRequest = new StringRequest(
                Request.Method.POST,
                "URL_TO_YOUR_WEB_API",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
    
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Failed to upload image.", Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
    
                // Converting Bitmap to String
                String image = getStringImage(mBitmap);
    
                // Create parameters
                Map<String, String> params = new Hashtable<>();
    
                // Add parameters
                params.put("action", "YOUR_BACKEND_KEY1");
                params.put("...", image);
    
                // Returning parameters
                return params;
            }
        };
    
        // Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
    
        // Adding request to the queue
        requestQueue.add(stringRequest);
    }
    

    Make sure to replace the parameter strings with however you have created your backend in php.

    Example URL:

    http://yoursite.com/api.php?action=uploadimage&imagebase=adwtgiuewohnjsoiu&caption=somecaptiontext
    

    Then the parameters in android would be:

    params.put("action", "uploadimage");
    params.put("imagebase", image);
    params.put("caption", "somecaptiontext");
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题