2012-09-14 12 views
6

こんにちは私は次のコードを使用して画像とテキストをphp webserviceに送信しています。androidからMultipartEntityを使用して複数の画像をサーバーに送信する方法

try { 


      HttpClient httpClient = new DefaultHttpClient(); 
      HttpContext localContext = new BasicHttpContext(); 
      HttpPost httpPost = new HttpPost(URL); 

      MultipartEntity entity = new MultipartEntity(
        HttpMultipartMode.BROWSER_COMPATIBLE); 

      ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
      bitmap.compress(CompressFormat.JPEG, 75, bos); 
      byte[] data = bos.toByteArray(); 

      entity.addPart("files[]", 
        new ByteArrayBody(data, "myImage.jpg")); 

      entity.addPart("message0", new StringBody(caption.getText() 
        .toString())); 

      httpPost.setEntity(entity); 
      HttpResponse response = httpClient.execute(httpPost, 
        localContext); 
      BufferedReader reader = new BufferedReader(
        new InputStreamReader(
          response.getEntity().getContent(), "UTF-8")); 

      String sResponse = reader.readLine(); 
      return sResponse; 
     } catch (Exception e) { 
      if (dialog.isShowing()) 
       dialog.dismiss(); 
      Toast.makeText(ImageUpload.this, e.getMessage(), 
        Toast.LENGTH_LONG).show(); 
      Log.e(e.getClass().getName(), e.getMessage(), e); 
      return null; 
     } 

    } 

これは完全に機能します。しかし、これはただ1つのイメージを送信するためのものです。今は5枚の画像とテキストを送っています。

例: - 画像1 - [テキスト1
画像2 - [テキスト2]など。

だから私は5画像を1枚ずつを保存する方法について混乱させ、最終的にサーバに関連付けられた画像やテキストを送信]をクリックし提出しています。

カメラからのイメージです。

Intent intent = new Intent(); 
      intent.setType("image/*"); 
      intent.setAction(Intent.ACTION_GET_CONTENT); 
      startActivityForResult(
        Intent.createChooser(intent, "Select Picture"), 
        PICK_IMAGE); 


public void onActivityResult_photo(int requestCode, int resultCode, 
     Intent data) { 
    // TODO Auto-generated method stub 
    if (resultCode == RESULT_OK) { 

     if (data != null) { 
      mImageCaptureUri = data.getData(); 
      display(mImageCaptureUri); 
     } else { 
      Toast.makeText(CustomTabActivity.mTabHost.getContext(), 
        "No photo selected..", Toast.LENGTH_SHORT).show(); 
     } 

    } 

} 


private String display(Uri mImageCaptureUri2) { 
    // TODO Auto-generated method stub 
    String base64string = null; 
    try { 

     if (mImageCaptureUri2 != null) { 

      System.gc(); 

      selectedImagePath = getPath(mImageCaptureUri2); 

      File filenew = new File(selectedImagePath); 
      int file_size = Integer.parseInt(String.valueOf(filenew 
        .length()/1024)); 
      if (file_size <= 10000) { 
       PD1 = ProgressDialog.show(
         CustomTabActivity.mTabHost.getContext(), "", 
         "Loading..."); 
       Handler refresh = new Handler(Looper.getMainLooper()); 

       refresh.post(new Runnable() { 
        public void run() { 

         PD1.setCancelable(true); 
         Bitmap newbitmap; 
         newbitmap = decodeFile(selectedImagePath); 
         ByteArrayOutputStream bs = new ByteArrayOutputStream(); 
         newbitmap.compress(Bitmap.CompressFormat.PNG, 50, 
           bs); 
         img.setVisibility(View.VISIBLE); 
         img.setImageBitmap(newbitmap); 
         byte[] abc = bitmapToByteArray(newbitmap); 
         if (txt_phototext.getText().toString().equals("")) { 
          submit.put(abc, ""); 
         } else { 
          submit.put(abc, txt_phototext.getText() 
            .toString()); 

          // executeMultipartPost(); 
         } 
         PD1.dismiss(); 

        } 
       }); 

      } else { 
       AlertDialog.Builder alertbox = new AlertDialog.Builder(
         CustomTabActivity.mTabHost.getContext()); 
       alertbox.setMessage("Take Image Size Less than 10 MB"); 
       alertbox.setNeutralButton("Ok", 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface arg0, 
            int arg1) { 
           finish(); 
          } 
         }); 
       alertbox.show(); 
      } 

     } else { 
      System.out.println("===============NULL========"); 
     } 

    } catch (Exception e) { 
     // // TODO Auto-generated catch block 
     // e.printStackTrace(); 
    } 
    return base64string; 
} 




    static Bitmap decodeFile(String str) { 
    try { 
     // decode image size 
     BitmapFactory.Options o = new BitmapFactory.Options(); 
     o.inJustDecodeBounds = true; 
     BitmapFactory.decodeStream(new FileInputStream(str), null, o); 

     // Find the correct scale value. It should be the power of 2. 
     final int REQUIRED_SIZE = 70; 
     int width_tmp = o.outWidth, height_tmp = o.outHeight; 
     int scale = 1; 
     while (true) { 
      if (width_tmp/2 < REQUIRED_SIZE 
        || height_tmp/2 < REQUIRED_SIZE) 
       break; 
      width_tmp /= 2; 
      height_tmp /= 2; 
      scale++; 
     } 

     // decode with inSampleSize 
     BitmapFactory.Options o2 = new BitmapFactory.Options(); 
     o2.inSampleSize = scale; 
     return BitmapFactory.decodeStream(new FileInputStream(str), null, 
       o2); 
    } catch (FileNotFoundException e) { 
    } 
    return null; 
} 




public static byte[] bitmapToByteArray(Bitmap bitmap) { 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos); 
    byte[] bitmapdata = bos.toByteArray(); 
    return bitmapdata; 
} 

だから最後に私はこのことに固執しています。

+0

[サーバーへの複数のファイルのアップロード](http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string -parameters-in-android /)[jarファイルはこれを追加する必要があります](http://stackoverflow.com/questions/2017414/post-multipart-request-with-android-sdk)これはあなたの問題を解決するのに役立ちます問題。 – Harish

答えて

0

そして、サーバーのディレクトリまたはフォルダが実行可能、書き込み可能、​​読み取り可能であることを確認してください。私はこれを大きな問題として抱えていました。これは777の許可と呼ばれています。私が信じていることは、これが他のものと同じくらい重要なことです。

0

はWAMPサーバ

-1

でyoutはphp.iniファイルのpost_max_sizeのを増やしてみてください、以下の方法を見つけてください...ここで私はAQUERYを使用してみとめた画像ファイルを送信メートル。すべてのバックグラウンドネットワーク関連のタスクを実行するための最良のlib(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

MultipartEntityを使用してサーバーに複数の画像を送信するために、その非常に困難私のポストにClick here

をご覧下さい。私はこのために検索しましたが、任意の適切なソリューションが、私は、ここで私はasynctaskとasynctaskに私は、サーバーに画像を送っするために選択したパスの配列を送信するサーバー に複数の画像を送信するために自分の道を作った見つけることができませんでした

Asysnctask機能 - を呼び出す

新しい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"); 

    } 
} 

//)。 **

画像を圧縮し、私は目的球の下に作られたのビットマップを取得するための
  • *

    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; 
    

    }

  • サーバーの終了コード*

    $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

あなたのリンクは 'Account Suspended'と表示されています – MilapTank

+0

なぜ画像のjsonオブジェクトの配列をbase64に作成し、サーバーにポストし、サーバー上でapiがバイトに変換して使用するのはなぜですか画像として。 –

0

なぜあなたは 'あなたのイメージのjsonオブジェクトの配列をbase64に作成し、サーバーにポストし、サーバーapiでこれらのイメージをバイトに変換してイメージとして使用します。 私の答えを確認し、実装しようとする。 In Android how to post data to webservice which is created in WCF?

カメラから取得した画像は、それらをuriでsdcardに保存し、手紙はそれらを読み取ります。イメージ名をsequntialyに割り当てることができます。そして、それらをuriから読んでください。

+0

大きな画像ベースの場合、64文字列は実際に大きくなり、時には完全に送信されないことがあるためです。そのため、ファイルとしてアップロードする方が良い方法です。 –

関連する問題