如何使用Volley上传图片到服务器?

8

我正在尝试使用Volley来发布我的数据,但我无法将我的图像上传到服务器。始终会出现错误,例如对于http:\\www.mybaseurl.com/upload.php的意外响应代码500。以下是我尝试上传的代码:

 public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

private void uploadImage(){
    //Showing the progress dialog
    final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //Disimissing the progress dialog
                    loading.dismiss();
                    //Showing toast message of the response
                    Toast.makeText(MainActivity.this, s , Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();

                    //Showing toast
                    Toast.makeText(MainActivity.this, ""+volleyError, Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //Converting Bitmap to String
            String image = getStringImage(bitmap);
            //Getting Image Name
            String name = editTextName.getText().toString().trim();
            //Creating parameters
            Map<String,String> params = new Hashtable<String, String>()
            params.put("empsno", "81");
            params.put("storesno", "165");
            params.put("lrSno", "1808");
            params.put("recQty", "0");
            params.put("recVol", "0");
            params.put("recWgt", "0");
            params.put("damageQty", "0");
            params.put("looseQty", "0");
            params.put("deliveryDate", "2016-09-24");
            params.put("deliveryTime", "10:15");
            params.put("uploadFile", image);
            params.put("remarks", "mytestingrem");
            params.put("receivedBy", "amankumar");
            params.put("ipAddress", "12.65.65.32");

            //returning parameters
            return params;
        }
    };

    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
}

private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}

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

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri filePath = data.getData();
        try {
            //Getting the Bitmap from Gallery
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            //Setting the Bitmap to ImageView
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void onClick(View v) {

    if(v == buttonChoose){
        showFileChooser();
    }

    if(v == buttonUpload){
        uploadImage();
    }
}

请帮我,如何使用这些参数上传文件。我对Volley不熟悉。我只是从https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server复制粘贴了这段代码。我甚至不知道我是否使用正确。

谢谢!

你可以分享你的PHP代码吗? - Adi
@Adi 我不了解 PHP 代码。我只知道参数,并且使用 rest (Chrome 扩展)向服务器发送数据。 - AMAN SINGH
@NessTyagi 谢谢兄弟...我也来试试这种方法。我尝试过使用 Retrofit 但没有成功。 - AMAN SINGH
@NessTyagi 我尝试了相同的链接,这段代码也是从相同的链接中获取的。我在问题上面也提供了这个链接。 - AMAN SINGH
您可以查看此教程,该教程使用Volley Multipart请求将图像上传到服务器。https://www.simplifiedcoding.net/upload-image-to-server/ - Shreyas Sanil
显示剩余2条评论
2个回答

12

你可以尝试这种方法,它在我的项目中实际有效。首先,您必须从相册中选择图像,然后将其转换为字符串并通过Volley发送到服务器。

// initialize
   private int PICK_IMAGE_REQUEST = 1;

    //set click listener 
         Upload.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //method to upload the image
                         showFileChooser();
       
                    }
                });
        

打开相册并选择图像的方法

                 private void showFileChooser() {
                     Intent pickImageIntent = new Intent(Intent.ACTION_PICK,
                 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                pickImageIntent.setType("image/*");
                                pickImageIntent.putExtra("aspectX", 1);
                                pickImageIntent.putExtra("aspectY", 1);
                                pickImageIntent.putExtra("scale", true);
                                pickImageIntent.putExtra("outputFormat",
                                Bitmap.CompressFormat.JPEG.toString());
                                startActivityForResult(pickImageIntent, PICK_IMAGE_REQUEST); 
                         }
              

添加这个方法。在这里,图像实际上正在被发送到服务器。

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                        super.onActivityResult(requestCode, resultCode, data);
                        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                            Uri filePath = data.getData();
                            try {
                                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                                Bitmap lastBitmap = null;
                                lastBitmap = bitmap;
                               //encoding image to string  
                                String image = getStringImage(lastBitmap);
                                Log.d("image",image);
                                //passing the image to volley
                                SendImage(image);
                         
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
        
       

 

将图像转换为字符串的方法

 public String getStringImage(Bitmap bmp) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        byte[] imageBytes = baos.toByteArray();
                        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
                        return encodedImage;
                
                    }
            
    



    

使用Volley上传

 private void SendImage( final String image) {
            final StringRequest stringRequest = new StringRequest(Request.Method.POST, "URL",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.d("uploade",response);
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                               
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
    
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(Edit_Profile.this, "No internet connection", Toast.LENGTH_LONG).show();
                           
                        }
                    }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
    
                    Map<String, String> params = new Hashtable<String, String>();
                  
                    params.put("image", image);
                    return params;
                }
            };
            {
                int socketTimeout = 30000;
                RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                stringRequest.setRetryPolicy(policy);
                RequestQueue requestQueue = Volley.newRequestQueue(this);
                requestQueue.add(stringRequest);
            }
        }

5
你还应该提到,使用base64编码会使图像数据膨胀约30%左右。 - TheRealChx101

7

要使用Volley库和上传图片,您需要了解相关概念。以下是一些有关上传图片和使用Volley库的其他有用链接:

Volley库

使用multipart上传图片

注意:我已经测试了您的教程,代码没有问题。请确保正确设置您的图片路径,并在任何托管的Web服务器上使用他们的php代码。检查他们的JSON响应并交叉检查您传递给服务器脚本参数的参数。


如果我直接插入获取图像的代码,会出现以下错误:**BasicNetwork.performRequest: Unexpected response code 500 for "http://example.com/upload"**。直接指的是http://pastebin.com/N3iegMU8。 - AMAN SINGH
请具体说明,我不知道您在哪里插入代码。 - Adi
这是一个非常简单和优秀的教程。你必须对基本的PHP概念有一些了解(包括数据库的基本查询)。我再次强调你丢失了图片路径。 - Adi
但我正在使用imageView,我成功获取了图像。 - AMAN SINGH
我按照相同的教程并复制了所有内容,只是更改了我的参数。 - AMAN SINGH
我的日志:net.simplifiedcoding.volleyupload E/Volley:[19262] BasicNetwork.performRequest:对http://267.2.2.1/upload.php的请求返回了意外的响应代码500。 - AMAN SINGH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接