How to send multiple images to server using MultipartEntity from android

前端 未结 5 1161
Happy的楠姐
Happy的楠姐 2020-11-30 08:07

Hello I am sending Images and Text to php webservice using following code.

try {


            HttpClient httpClient = new DefaultHttpClient();
            H         


        
相关标签:
5条回答
  • 2020-11-30 08:41

    And make sure that your directory or folder in server is Executable, Writable and Readable. I had this as the major problem. This is called 777 permission.. Believe me, this is as important as other things to consider.

    0 讨论(0)
  • 2020-11-30 08:43

    For full detail please have a look on my post Click here

    its quite difficult to send multiple images to server using MultipartEntity. I did search for this but didn't find any right solution then i made my own way to send multiple images to server , here i send array of selected paths to asynctask and in asynctask i sent images to server

    Calling Asysnctask Function- new Upload_Multiple.excute(Array_of_Path[]))

        Private class Upload_Multiple_img extends AsyncTask<String, Void, String> {
    
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
    
        }
    
        protected String doInBackground(String... paths_array) {
    
    
    
            String data = "";
    
            for (int i = 0; i < paths_array.length; i++) {
    
                //  get_Picture_bitmap() returns bitmap by passing path of image 
                 //   get_Picture_bitmap() is mentioned below. 
                Bitmap bitmap = get_Picture_bitmap(paths_array[i]);
    
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
    
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert
    
                DefaultHttpClient httpclient = new DefaultHttpClient();
    
                String server_funtion_url="...serveraddres"+funtion_at_server"";
                HttpPost httppost = new HttpPost(server_funtion_url); // server
    
                MultipartEntity reqEntity = new MultipartEntity();
    
                obj_SP = ImagePicker.this.getSharedPreferences("Eperty", 0);
    
                String id_prop = obj_SP.getString("new_prop_id", "");
    
                String Image_Name =
                        + String.valueOf(System.currentTimeMillis()) + ".jpg";
    // image is a key which is used at server end to get this 
                reqEntity.addPart("image", Image_Name, in);
    
                httppost.setEntity(reqEntity);
    
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httppost);
                    data = EntityUtils.toString(response.getEntity());
                    System.out.println("FFFF== " + data);
    
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
    
                }
    
            }
    
            return data;
        }
    
        @Override
        protected void onProgressUpdate(Void... values) {
    
            super.onProgressUpdate(values);
        }
    
        @Override
        protected void onPostExecute(String result) {
    
            ConstantData.ToastAlert(ImagePicker.this,
                    "Images Uploaded successfully");
    
        }
    }
    

    //);

    • For compressing the images and getting bitmap for i made below funtion*

      public Bitmap get_Picture_bitmap(String imagePath) {
      
      long size_file = getFileSize(new File(imagePath));
      
      size_file = (size_file) / 1000;// in Kb now
      int ample_size = 1;
      
      if (size_file <= 250) {
      
          System.out.println("SSSSS1111= " + size_file);
          ample_size = 2;
      
      } else if (size_file > 251 && size_file < 1500) {
      
          System.out.println("SSSSS2222= " + size_file);
          ample_size = 4;
      
      } else if (size_file >= 1500 && size_file < 3000) {
      
          System.out.println("SSSSS3333= " + size_file);
          ample_size = 8;
      
      } else if (size_file >= 3000 && size_file <= 4500) {
      
          System.out.println("SSSSS4444= " + size_file);
          ample_size = 12;
      
      } else if (size_file >= 4500) {
      
          System.out.println("SSSSS4444= " + size_file);
          ample_size = 16;
      }
      
      Bitmap bitmap = null;
      
      BitmapFactory.Options bitoption = new BitmapFactory.Options();
      bitoption.inSampleSize = ample_size;
      
      Bitmap bitmapPhoto = BitmapFactory.decodeFile(imagePath, bitoption);
      
      ExifInterface exif = null;
      try {
          exif = new ExifInterface(imagePath);
      } catch (IOException e) {
          // Auto-generated catch block
          e.printStackTrace();
      }
      int orientation = exif
              .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
      Matrix matrix = new Matrix();
      
      if ((orientation == 3)) {
          matrix.postRotate(180);
          bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
                  bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
                  true);
      
      } else if (orientation == 6) {
          matrix.postRotate(90);
          bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
                  bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
                  true);
      
      } else if (orientation == 8) {
          matrix.postRotate(270);
          bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
                  bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
                  true);
      
      } else {
          matrix.postRotate(0);
          bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
                  bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
                  true);
      
      }
      
      return bitmap;
      

      } **

    • Server end Code *

      $target_dir = "../webadmin/user_image/";
      $target_dir = $target_dir . basename($_FILES["user_img"]["name"]);
      if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_dir))
        {
           $msg = "The file ". basename($result[0]). " has been uploaded.";
           $send_arr['success'] = 1;
           $send_arr['message'] = $msg;
           echo json_encode($send_arr);
        }
      else 
        {
           $msg = "Sorry, there was an error uploading your file.";
           $send_arr['success'] = 0;
           $send_arr['message'] = $msg;
           echo json_encode($send_arr);
        }
      
    0 讨论(0)
  • 2020-11-30 08:49

    Try increasing the post_max_size of yout php.ini file in WAMP server

    0 讨论(0)
  • 2020-11-30 08:59

    Why you can't just create array of json object of your images to base64 and post to server and at your server api read those images convert to byte and use as image. Check my answe and try to implement. In Android how to post data to webservice which is created in WCF?

    And the images you are getting from camera store them in uri in sdcard and letter read them. You can assign image name sequntialy. And read them from uri.

    0 讨论(0)
  • 2020-11-30 09:04

    Please find the below method...here i m sending mutiple image file using AQUERY. The best lib to perform all background network related task.(Like AJAX).

    https://code.google.com/p/android-query/

       public void uploadImageFile( String filePath,
                String message) {
    
            Context context = ApplicationContextProvider.getContext();
            String url = SERVER_URL + "/user/uploadImageFile";
    
    
                try {
                    Toast.makeText(context, "Uploading...", Toast.LENGTH_SHORT)
                            .show();
    
                    String compressedFile = CommonUtilities.compressImage(filePath,
                            context);
    
                    Map<String, Object> params = new HashMap<String, Object>();
    
    
                    File imageFile = new File(compressedFile);
                    byte[] imageBytes1 = FileUtils.readFileToByteArray(imageFile);
                    params.put("imageBytes", imageBytes1);
                    params.put("message",URLEncoder.encode(message, "UTF-8"));
    
    
                    AQuery aq = new AQuery(context);
                    aq.ajax(url, params, JSONObject.class,
                            new AjaxCallback<JSONObject>() {
                                @Override
                                public void callback(String url, JSONObject json,
                                        AjaxStatus status) {
                                    Toast.makeText(
                                            ApplicationContextProvider.getContext(),
                                            "Uploaded successfully",
                                            Toast.LENGTH_SHORT).show();
    
    
    
                                }
                            });
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT)
                            .show();
                }
    
        }
    
    0 讨论(0)
提交回复
热议问题