使用Base64OutputStream将字符串上载到服务器-Android

使用Base64OutputStream将字符串上载到服务器-Android,android,base64,photo,Android,Base64,Photo,我一直在使用此代码,但遇到了一些内存问题: // Get the image from the sdcard Bitmap bm = BitmapFactory.decodeFile("/sdcard/myimage.jpg"); // turn image into byte array output stream ByteArrayOutputStream baos = new ByteArrayOutputStream();

我一直在使用此代码,但遇到了一些内存问题:

      // Get the image from the sdcard
      Bitmap bm = BitmapFactory.decodeFile("/sdcard/myimage.jpg");
      // turn image into byte array output stream
      ByteArrayOutputStream baos = new ByteArrayOutputStream();  
      // 'compress' the jpeg
      bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);               
      // get byte[] array of the image        
      byte[] byteArray = baos.toByteArray();
      // turn image into base64 string        
      String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
      // and base64 string to 'params' value pair        
      params.add(new BasicNameValuePair("userfile", encodedImage));

      try {
       HttpPost request = new HttpPost();

       String urlString = "http://www.example.com";
       request.setURI(new URI(urlString));

     if(params != null) {
        request.setEntity(new UrlEncodedFormEntity(params));
        HttpClient client = new DefaultHttpClient();
        client.execute(request);
     } // end if
} // end try
有人建议我应该使用
Base64OutputStream
而不是
Base64.encodeToString
,但我没有成功地使用
Base64OutputStream
输出可以上传到服务器的字符串。任何在图像上使用
Base64OutputStream
的示例都会非常有帮助

编辑

为了让答案生效,您需要向Android项目添加两个文件:apache-mime4j-dom-0.7.2.jar和httpmime-4.1.3.jar

您可以从以下位置下载apache-mime4j-dom-0.7.2.jar-下载二进制文件,解压缩它,然后找到apache-mime4j-dom-0.7.2.jar文件

然后转到并下载httpmime-4.1.3.jar


然后将这两个文件拖到Eclipse中的项目中。然后在Eclipse中,选择项目>属性。选择属性弹出窗口,选择Java构建路径。单击“库”选项卡(查找源|项目|库|订购和导出)。单击“添加jar”,选择apache-mime4j-dom-0.7.2.jar和httpmime-4.1.3.jar;然后单击“订单和导出”选项卡。检查apache-mime4j-dom-0.7.2.jar和httpmime-4.1.3.jar;然后关闭弹出窗口并从Eclipse菜单中选择Project>Clean

如果可能,您不应该对文件进行Base64编码并以URL发送,而应该使用多部分文件上载:

HttpPost post = new HttpPost(URL);
HttpClient client = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );

// picture
entity.addPart( "userfile", new FileBody( 
    new File( MyApp.getContext().getFilesDir(), "userfile.jpg" ),
    "image/jpeg")
);

entity.addPart( "blahblah", new StringBody( "blah" ));  // string value

post.setEntity( entity );
client.execute( post );

你能告诉我从哪里弄到这个罐子,这样我就可以使用MultipartEntity了吗?我以前试过这个,从apache下载了我能找到的所有东西,但似乎都不起作用。我编辑了原始帖子,以显示从何处获取JAR文件以及如何将它们添加到您的项目中。@Chris:很抱歉,迟到了,您已经找到了这些文件。