0

我想将图像和文本数据发布到服务器。当我发送数据时,它只发送文本数据,而不发送图像。

public class MainActivity extends Activity implements
    android.view.View.OnClickListener {

private static final int SELECT_PICTURE = 0;
Bitmap bm;
ImageView img;
EditText edittext;
Button btn;
String imgtype, img1;
JSONObject jobj;
File fileToUpload = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (android.os.Build.VERSION.SDK_INT > 8) {

        StrictMode.ThreadPolicy th = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(th);

    }

    btn = (Button) findViewById(R.id.button1);
    edittext = (EditText) findViewById(R.id.editText1);
    btn.setOnClickListener(this);

    img = (ImageView) findViewById(R.id.imageView1);
    img.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    switch (v.getId()) {
    case R.id.imageView1:
        PhotoFromGallery();
        break;
    case R.id.button1:
        // upload();

        upload();

        break;
    default:
        break;
    }

}

public void PhotoFromGallery() {
    Intent i = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    startActivityForResult(i, SELECT_PICTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case SELECT_PICTURE:

        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            if (bm != null && bm.isRecycled()) {

                bm = null;
            }
            bm = BitmapFactory.decodeFile(picturePath);
            img.setImageBitmap(bm);

        }
    }

}

private void upload() {
    try {

        String a = edittext.getText().toString();
        // img1=img.setImageBitmap(bm);

        // URL url = new URL(
        String URL_BASE = "yoururl";

        String url1 = String
                .format(URL_BASE
                        + "description_comment_=%s&member_id_comment_=%s&product_id_comment_=%s&store_id_comment_=%s",
                        a, 1, 191, 55);

        URL url = new URL(url1);

        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        // this HTTP request will involve input
        c.addRequestProperty("app_key", "rg946A");
        c.addRequestProperty("description", edittext.getText().toString());
        // c.addRequestProperty("categories", SelcectItem);
        c.setDoInput(true);
        // should be PUT or POST to follow convention
        c.setRequestMethod("POST");
        System.out.println(c.getRequestProperties().toString());
        // this HTTP request will involve output
        c.setDoOutput(true);
        // open the HTTP connection
        c.connect();
        OutputStream output = c.getOutputStream();
        // compress and write the image to the output stream
        bm.compress(CompressFormat.JPEG, 100, output);

        output.close();

        System.out.println(c.getResponseMessage());
        if (c.getResponseMessage().equalsIgnoreCase("OK")) {
            edittext.setText("");
            img.setImageResource(R.drawable.ic_launcher);

            Toast.makeText(
                    getApplicationContext(),
                    "Picture Upload Successfully..\n"
                            + "Picture will be available after admin approval",
                    Toast.LENGTH_LONG).show();
        }

    } catch (IOException e) {
        // log error
        e.printStackTrace();
        Log.e("ImageUploader", "Error uploading image", e);
    }
    }

}
4

1 回答 1

2

确保在后台线程上进行上传(使用 asynctask 在 doInbackground() 中进行上传)。您需要图像文件路径。

我在我的一个应用程序中使用了以下内容,它对我有用。

 public void upload(String filepath) throws IOException
    {
     HttpClient httpclient = new DefaultHttpClient();
     httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
     HttpPost httppost = new HttpPost("url");
     File file = new File(filepath);
     MultipartEntity mpEntity = new MultipartEntity();
     ContentBody cbFile = new FileBody(file, "image/jpeg");
     mpEntity.addPart("userfile", cbFile); 
     httppost.setEntity(mpEntity);
     System.out.println("executing request " + httppost.getRequestLine());
     HttpResponse response = httpclient.execute(httppost);
     HttpEntity resEntity = response.getEntity();
             // check the response and do what is required
      }

上传完成后关闭http连接

      httpclient.getConnectionManager().shutdown(); 

使用下面评论中提供的 url 运行上述代码片段的 logcat 信息

  05-29 19:45:16.740: I/System.out(3594): executing request.......... POST    http://www.sevenstarinfotech.com/projects/demo/okaz/API/add_comments.php?description_comment_=add%2520comment&member_id_comment_=1&product_id_comment_=126&store_id_comment_=0 HTTP/1.1
 05-29 19:45:19.505: I/System.out(3594): .................responseHTTP/1.1 200 OK
 05-29 19:45:19.510: I/System.out(3594): .................response{"data": {"Success":"1","Message":"Comment successfully posted.","commentsid":376}}
于 2013-05-28T13:42:28.333 回答