以base64格式上传图片。应用程序崩溃

时间:2013-05-23 13:10:14

标签: android image http upload

我正在尝试通过网络上传图片,但我的应用程序在bw中不断崩溃 我的代码是

  package com.example.imgeup;

  import java.io.ByteArrayOutputStream;
  import java.io.File;
  import java.io.InputStream; 
  import java.util.ArrayList;

  import org.apache.http.HttpEntity;
  import org.apache.http.HttpResponse;
  import org.apache.http.NameValuePair;
  import org.apache.http.client.HttpClient;
  import org.apache.http.client.entity.UrlEncodedFormEntity;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.impl.client.DefaultHttpClient;
  import org.apache.http.message.BasicNameValuePair;

  import android.os.Bundle;
  import android.os.Environment;
  import android.app.Activity;
  import android.graphics.Bitmap;
  import android.graphics.BitmapFactory;
  import com.example.imgeup.Base64;

  import com.loopj.android.http.AsyncHttpClient;
  import com.loopj.android.http.AsyncHttpResponseHandler;
  import com.loopj.android.http.RequestParams;

  import android.util.Log;
  import android.view.Menu;
  import android.view.View;
  import android.widget.ImageView;
  import android.widget.Toast;

  public class MainActivity extends Activity {
  ImageView mv;
  InputStream is;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mv = (ImageView)findViewById(R.id.imageView1);
}

public void Button(View view)
{



    try{
    //String path = "/mnt/sdcard/Pictures/IWMP-Images/IMG_20130523_164101.jpg";
       String path = Environment.getExternalStorageDirectory()+ "/Pictures/IWMP-Images/IMG_20130523_161730.jpg"; 
       File imgFile = new File(path);
       if(imgFile.exists())
   {
           Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());                  

           mv.setImageBitmap(myBitmap);
           ByteArrayOutputStream baos = new ByteArrayOutputStream();  
           myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
           byte[] b = baos.toByteArray();
          // String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
          String ba1=Base64.encodeBytes(b);
         //  String ba1="hi";
           ArrayList<NameValuePair> nameValuePairs = new

                   ArrayList<NameValuePair>();

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

                   try{

                  /* HttpClient httpclient = new DefaultHttpClient();

                   HttpPost httppost = new

                   HttpPost("http://192.168.1.4:80/up.php");
                   httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                   HttpResponse response = httpclient.execute(httppost);

                   HttpEntity entity = response.getEntity();

                   is = entity.getContent();*/


                       AsyncHttpClient client = new AsyncHttpClient();
                        RequestParams rp = new RequestParams();
                        rp.put("image", ba1);
                        client.post("http://192.168.1.4:80/up.php", rp, new AsyncHttpResponseHandler() {
                            public final void onSuccess(String response) {
                                 Toast.makeText(getApplicationContext(),"SUCCESS", Toast.LENGTH_LONG).show();
                            }

                            @Override
                            public void onFailure(Throwable e, String response) {
                                e.printStackTrace();
                                 Log.d("Exception", e.toString());
                                 Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
                            }               
                        });
                   }
                   catch(Exception e){

                   Log.e("log_tag", "Error in http connection "+e.toString());

                   }


   }
       else                    
           Toast.makeText(this.getBaseContext(),"no IMAGE IS PRESENT'",Toast.LENGTH_SHORT).show();
   }
    catch(Exception e)
    {
        System.out.println(e.toString());
    }
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
  }

当使用简单的ba1 =“hi”时,吐司打印SUCCESS但是当它与base64一起使用时,它会崩溃。同时在base64中转换图像时需要花费大量时间..任何关于hw的想法都可以减少这种情况。 请帮助谢谢..

我的php也是

`

     $base=$_REQUEST['image'];

     //echo $base;

     // base64 encoded utf-8 string

     $binary=base64_decode($base);

     // binary, utf-8 bytes

     header('Content-Type: bitmap; charset=utf-8');

     print($binary);

     //$theFile = base64_decode($image_data);

      //$file = fopen('test.jpg', 'wb');

      //fwrite($file, $binary);

     //fclose($file);

     //echo '<img src=test.jpg>';

 ?>

我参考了 http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/

我的日志.error

`

 05-23 18:51:27.719: E/dalvikvm-heap(7622): Out of memory on a 14862728-byte allocation.

    05-23 18:51:27.782: E/AndroidRuntime(7622): FATAL EXCEPTION: main

    05-23 18:51:27.782: E/AndroidRuntime(7622): java.lang.IllegalStateException: Could not execute method of the activity

    05-23 18:51:27.782: E/AndroidRuntime(7622):     at android.view.View$1.onClick(View.java:2082)

    05-23 18:51:27.782: E/AndroidRuntime(7622):     at android.view.View.performClick(View.java:2461)

    05-23 18:51:27.782: E/AndroidRuntime(7622):     at android.view.View$PerformClick.run(View.java:8890)

    05-23 18:51:27.782: E/AndroidRuntime(7622):     at android.os.Handler.handleCallback(Handler.java:587)

    05-23 18:51:27.782: E/AndroidRuntime(7622):     at android.os.Handler.dispatchMessage(Handler.java:92)


   05-23 18:51:27.782: E/AndroidRuntime(7622):  at
 android.os.Looper.loop(Looper.java:123)


   05-23 18:51:27.782: E/AndroidRuntime(7622):  at    android.app.ActivityThread.main(ActivityThread.java:4632)


   05-23 18:51:27.782: E/AndroidRuntime(7622):  at java.lang.reflect.Method.invokeNative(Native Method)

    05-23 18:51:27.782: E/AndroidRuntime(7622):     at java.lang.reflect.Method.invoke(Method.java:521)

    05-23 18:51:27.782: E/AndroidRuntime(7622):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)

    05-23 18:51:27.782: E/AndroidRuntime(7622):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at dalvik.system.NativeStart.main(Native Method)

  05-23 18:51:27.782: E/AndroidRuntime(7622): Caused by: java.lang.reflect.InvocationTargetException

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at com.example.imgeup.MainActivity.Button(MainActivity.java:89)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at java.lang.reflect.Method.invokeNative(Native Method)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at java.lang.reflect.Method.invoke(Method.java:521)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at android.view.View$1.onClick(View.java:2077)

   05-23 18:51:27.782: E/AndroidRuntime(7622):  ... 11 more

  05-23 18:51:27.782: E/AndroidRuntime(7622): Caused by: java.lang.OutOfMemoryError

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:97)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at    java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:144)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at java.lang.StringBuffer.append(StringBuffer.java:126)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at java.net.URLEncoder.encode(URLEncoder.java:111)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at org.apache.http.client.utils.URLEncodedUtils.encode(URLEncodedUtils.java:184)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at org.apache.http.client.utils.URLEncodedUtils.format(URLEncodedUtils.java:163)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at org.apache.http.client.entity.UrlEncodedFormEntity.<init>(UrlEncodedFormEntity.java:57)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at com.loopj.android.http.RequestParams.getEntity(RequestParams.java:266)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at com.loopj.android.http.AsyncHttpClient.paramsToEntity(AsyncHttpClient.java:589)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at com.loopj.android.http.AsyncHttpClient.post(AsyncHttpClient.java:390)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   at com.loopj.android.http.AsyncHttpClient.post(AsyncHttpClient.java:379)

  05-23 18:51:27.782: E/AndroidRuntime(7622):   ... 15 more


`

1 个答案:

答案 0 :(得分:1)

如果这仍然是一个问题:您可以请求权限使用更多内存,而不是默认情况下在清单中允许的内存。但这仍然会限制您的上传到最大尺寸,甚至可能无法在所有设备上可靠地工作。

相反,我建议您查看this question,接受的答案显示了一种以小块方式传输文件的方法。