【问题标题】:How to upload Image on server using Volley?如何使用 Volley 在服务器上上传图像?
【发布时间】:2017-02-03 20:17:28
【问题描述】:

我正在尝试使用 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();
    }
}

请帮助我,如何使用这些参数上传文件。我是排球新手。我只是从 https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server 复制粘贴此代码。即使我不知道我是否正确使用。 提前致谢

【问题讨论】:

  • 检查一下techstricks.com/multipart-request-using-android-volley>.
  • 可以分享你的php代码吗?
  • @Adi php 代码我不知道。我只知道参数并使用 rest (chrome extensiong) 如何将数据发送到服务器
  • 有史以来最好的教程Upload Image On Server Using Volley 查看上面的链接。
  • @NessTyagi 谢谢兄弟......让我也检查一下。我尝试改造但没有成功

标签: android android-volley image-uploading


【解决方案1】:

你可以试试这个方法,它实际上对我的项目有效。首先你必须从图库中选择图像,然后必须将其转换为字符串并通过 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);
            }
        }

【讨论】:

  • 你还应该提到base64会将图像数据膨胀30%左右。
【解决方案2】:

您应该了解使用 volley 库和图像上传的概念。这里有一些其他有用的图片上传和使用 volley 库的链接。

volley library

Image upload using multipart

注意:我也测试过你的tutorial.code 没问题。请正确检查您的图像路径。如果可能的话,然后在任何托管的 Web 服务器上使用他们的 php 代码。并检查他们的 json 响应并交叉检查您通过服务器脚本参数传递的参数..

【讨论】:

  • 如果我直接插入我的图像代码得到此错误 BasicNetwork.performRequest: Unexpected response code 500 for "example.com/upload 直接表示pastebin.com/N3iegMU8
  • 请具体。我不喜欢你插入代码。
  • 它;如此简单和优秀的教程。你必须有一些基本的 php 概念(与数据库的基本查询)的知识。我再次说你缺少你的图像路径。
  • 但我正在使用 imageView ,我正在成功获取图像
  • 我遵循相同的教程并从那里复制所有内容,并简单地更改了我的参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 2016-12-06
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多