Android - 将2个文件发送到服务器

时间:2013-08-20 13:24:33

标签: android post multipartentity

我正在尝试创建一个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的导入jar,但我把它们放在项目的libs文件夹中,它们出现在Android私有库中。在我添加它们后,我刷新并清理了项目。 我在Eclipse中这样做,当我在模拟器中启动应用程序时,我可以拍摄照片,我可以从手机中选择一张照片,但是当我尝试上传它时,我收到错误。 如果有人有任何建议,我将不胜感激。

PS我没有忽略它,只是因为我没有对结果做任何事情。

1 个答案:

答案 0 :(得分: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是一个展示时间延长的祝酒词。