从Android应用上传图片

时间:2012-03-28 21:10:39

标签: android image image-uploading

在我的应用程序中,我将图像上传到服务器。在下面的代码中,我正在从drawable文件夹中上传图像。 但是如何从布局xml上传图像视图中的图像? 类似于 findviewbyid.imgid

我的布局名称是 main.xml ,图片ID是 imgid

请帮助我......

 Bitmap bitmap =
 BitmapFactory.decodeResource(getResources(),R.drawable.avatar);       
 ByteArrayOutputStream stream = new ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
 byte [] byte_arr = stream.toByteArray();
 String image_str = Base64.encodeBytes(byte_arr);
 ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

 nameValuePairs.add(new BasicNameValuePair("image",image_str));

1 个答案:

答案 0 :(得分:2)

我们可以使用Base64字符串和多部分实体上传图像

for base64 string

ByteArrayOutputStream baos = new ByteArrayOutputStream();
        btMap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the
        byte[] b = baos.toByteArray();
        base64String = Base64.encodeBytes(b);

和多部分

HttpPost httppost = new HttpPost("http://localhost:8080/upload.php");
File file = new File(yourimagepath);

MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();