2013-08-20 4 views
3

갤러리에서 2 개의 사진을 찍거나 서버로 보낼 수있는 Android 앱을 만들려고합니다. 코드 :Android - 서버에 2 개의 파일 보내기

private static final int SELECT_PICTURE = 1; 
private String selectedImagePath; 
private int TAKE_PHOTO_CODE = 0; 
private Uri outputFileUri; 

public void getit() { 
    Intent intentpic= new Intent(); 
    intentpic.setAction(Intent.ACTION_GET_CONTENT); 
    intentpic.setType("image/*"); 
    startActivityForResult(Intent.createChooser(intentpic, "Select Picture"), SELECT_PICTURE); 
} 

public void takepic() { 
    final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/IDandCCD/"; 
    File newdir = new File(dir); 
    newdir.mkdirs(); 

    String file=""; 
    if(but.equals(3)) { 
     file = dir+"ID"+".jpg"; 
    } 
    else if(but.equals(4)) { 
     file = dir+"CCD"+".jpg"; 
    } 
    File newfile = new File(file); 
    try { 
     newfile.createNewFile(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    }  

    outputFileUri = Uri.fromFile(newfile); 

    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); 

    startActivityForResult(cameraIntent, TAKE_PHOTO_CODE); 
} 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode == RESULT_OK) { 
     if (requestCode == SELECT_PICTURE) { 
      Uri selectedImageUri = data.getData();    
      selectedImagePath = getPath(selectedImageUri); 

      //selectedImagePath = selectedImageUri.getPath()+".jpg"; 

      if(but.equals(1)) { 
       id.setText(selectedImagePath); 
      } 
      else if(but.equals(2)) { 
       ccd.setText(selectedImagePath); 
      } 
     } 
     else if(requestCode == TAKE_PHOTO_CODE) { 
      String fname = outputFileUri.getPath(); 
      if(but.equals(3)) { 
       id.setText(fname); 
      } 
      else if(but.equals(4)) { 
       ccd.setText(fname); 
      } 
     } 
    } 
} 

@SuppressWarnings(value = { "deprecation" }) 
public String getPath(Uri uri) { 
    String[] projection = { MediaStore.Images.Media.DATA }; 
    Cursor cursor = managedQuery(uri, projection, null, null, null); 
    if(cursor!=null) 
    { 
     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
     cursor.moveToFirst(); 
     return cursor.getString(column_index); 
    } 
    else return null; 
} 
private class MyAsyncTask extends AsyncTask<String, Void, String> { 
    ProgressDialog pro1; 

    protected void onPostExecute(String result) { 
     pro1.dismiss(); 
     } 

    @Override 
    protected void onPreExecute() { 
     pro1 = ProgressDialog.show(ThirdStep.this, "Loading", "Please wait"); 
     } 

    @Override 
    protected String doInBackground(String... params) { 
     String hdfgs="tgabvds"; 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(params[0]); 
     String responseStr=null; 
     try { 
      MultipartEntity entity = new MultipartEntity(); 
      FileBody pic1=new FileBody(new File(id.getText().toString())); 
      FileBody pic2=new FileBody(new File(ccd.getText().toString())); 
      entity.addPart("idpic", pic1); 
      entity.addPart("ccdpic", pic2);    
      httppost.setEntity(entity); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity resEntity=response.getEntity(); 
      responseStr=resEntity.toString(); 
     } catch (Exception e) { 
      Log.e("Debug", "error: " + e.getMessage(), e); 
     } 
     return responseStr; 
     } 
    } 

는하지만 난 문제로 실행 : 처음에는

08-20 12:45:20.409: D/dalvikvm(2235): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE 
08-20 12:45:20.409: W/dalvikvm(2235): VFY: unable to resolve static field 2667 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueParser; 
08-20 12:45:20.482: D/dalvikvm(2235): VFY: replacing opcode 0x62 at 0x001b 
08-20 12:45:20.502: D/dalvikvm(2235): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueFormatter;.INSTANCE 
08-20 12:45:20.528: W/dalvikvm(2235): VFY: unable to resolve static field 2661 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueFormatter; 
08-20 12:45:20.528: D/dalvikvm(2235): VFY: replacing opcode 0x62 at 0x0015 
08-20 12:45:22.618: D/dalvikvm(2235): GREF has increased to 201 

는 내가 그것을 때문에 가져온 항아리의 MultipartEntity에 대한이었다 생각하지만 난 프로젝트의 libs와 폴더에 넣어 Android 개인 라이브러리에 표시됩니다. 내가 그들을 추가 한 후 나는 새로 고치고 프로젝트를 청소했다. Eclipse에서이 작업을 수행하고 있는데 에뮬레이터에서 앱을 시작하면 사진을 찍을 수 있습니다. 전화에서 사진을 선택할 수는 있지만 업로드하려고하면 오류가 발생합니다. 누구든지 제안 사항이 있으면 감사하게 생각합니다.

추신 : 나는 그것을 간과하지 않았으며, 그 결과로 아직 아무것도하지 않고있다.

+0

흠, Android에 이미 HttpClient 버전이 내장되어 있고 자신의 패키지를 꾸미려고하는 것처럼 들릴 수도 있습니다. Eclipse 프로젝트 설정에서 라이브러리가 내 보낸 것으로 표시되어 있습니까? 최근에 빌드 된 도구 업데이트로 인해 모든 라이브러리가 중단되었습니다. 이 경우에 깨진 lib는 내장 된 HttpClient를 대체하려고하는 대신 내장 된 HttpClient를 사용한다는 것을 의미하며 버전은 호환되지 않을 수 있습니다. –

+0

예, 프로젝트 속성에서 개인 라이브러리가 내 보낸 것으로 표시됩니다. 나는 HTTP 클라이언트가 문제를 일으키는 지 확신하지 못한다. 내 코드는이 웹 사이트에서 파일 업로드를 위해 multipart 엔티티를 사용하는 것에 대해 읽은 것과 매우 흡사하다. 나는 그것을 이해할 수 없다. – user1649498

답변

1

이 작업을 수행 할 수 없기 때문에 대신 Base64 인코딩과 BasicNameValuePair를 사용하여 해당 방식으로 업로드 할 수있었습니다. 질문에있는 코드에 무엇이 잘못되었는지 아이디어를 가지고 누군가 그것을 해결하는 방법을 알고 싶습니다.

이제 코드는 잘 다음 작품 :

private void filesToSend() { 
    File f1=new File(id.getText().toString()); 
    File f2=new File(ccd.getText().toString()); 
    if (f1.exists()&&f2.exists()) { 
     Bitmap bip1=BitmapFactory.decodeFile(f1.getAbsolutePath()); 
     Bitmap bip2=BitmapFactory.decodeFile(f2.getAbsolutePath()); 
     ByteArrayOutputStream stream1=new ByteArrayOutputStream(); 
     ByteArrayOutputStream stream2=new ByteArrayOutputStream(); 
     bip1.compress(Bitmap.CompressFormat.JPEG, 90, stream1); //compress to which format you want. 
     bip2.compress(Bitmap.CompressFormat.JPEG, 90, stream2); 
     byte [] byte_arr1=stream1.toByteArray(); 
     byte [] byte_arr2=stream2.toByteArray(); 
     image_str1=Base64.encodeToString(byte_arr1, Base64.DEFAULT); 
     image_str2=Base64.encodeToString(byte_arr2, Base64.DEFAULT); 
     RSet=true; 
    } 

다음 부분은 내 AsyncTask를에 있습니다

protected String doInBackground(String... params) { 
     String result=null; 
     String response=null; 
     ArrayList<NameValuePair> postparams=new ArrayList<NameValuePair>(); 
     postparams.add(new BasicNameValuePair("idpic", params[0])); 
     postparams.add(new BasicNameValuePair("ccdpic", params[1])); 
     try { 
      response=CustomHttpClient.executeHttpPost(params[2], postparams); 
      result=response.toString(); 
     } catch (Exception e) { 
      Log.e("Error", e.getMessage()); 
     } 
     return result; 
     } 

그리고 버튼 클릭에 : 나는

filesToSend(); 
      String url="http://10.0.2.2/Android/tstep.php"; 
      if(RSet.equals(true)) { 
       new MyAsyncTask().execute(image_str1, image_str2, url); 
      } 
      else if(RSet.equals(false)) { 
       tostVLong("The images are not set, please choose or take a picture before sending."); 
      } 

PS 이 사이트의 답변 중 하나에서 얻은 사용자 지정 http 클라이언트를 사용하여 어떤 웹 사이트인지 기억할 수 없습니다. ... tostVLong은 쇼 타임이 연장 된 축배입니다.