【问题标题】:Upload image to a server Android将图像上传到服务器 Android
【发布时间】:2014-03-21 02:36:27
【问题描述】:

我是安卓编程新手。所以我正在关注一些教程来学习它。我正在尝试将图像上传到 php 服务器。我已经按照这个教程http://monstercoda.wordpress.com/2012/04/15/android-image-upload-tutorial-part-i/

一切正常,但唯一的问题是我不知道在哪里编写此代码以及使用哪种方法。

HttpUploader uploader = new HttpUploader();
try {
  String image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();        
} catch (InterruptedException e) {
  e.printStackTrace();
} catch (ExecutionException e) {
  e.printStackTrace();
}

我试图在我的 onCreate MainActivity 方法或我的 MainUploader 类中编写此代码,但应用程序崩溃了。如果我不编写此代码,则应用程序可以工作,但显然我无法执行全部功能。

我在这里编写了导致应用程序崩溃的代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    HttpUploader uploader = new HttpUploader();
    try {
        image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    Button upload_btn = (Button) this.findViewById(R.id.uploadButton);
}

请告诉我在哪里可以放置上述代码。

【问题讨论】:

  • 你能发布堆栈跟踪,即崩溃后得到的错误日志吗?

标签: php android image-upload


【解决方案1】:

使用以下代码上传

 public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);           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));

         Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
              try{
                     HttpClient httpclient = new DefaultHttpClient();
                     HttpPost httppost = new HttpPost("http://10.0.2.2/Upload_image_ANDROID/upload_image.php");
                     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                     HttpResponse response = httpclient.execute(httppost);
                     String the_string_response = convertResponseToString(response);
                     runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();                          
                            }
                        });

                 }catch(Exception e){
                      runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();                              
                        }
                    });
                       System.out.println("Error in http connection "+e.toString());
                 }  
        }
    });
     t.start();
    }

    public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

         String res = "";
         StringBuffer buffer = new StringBuffer();
         inputStream = response.getEntity().getContent();
         int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
          runOnUiThread(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();                     
        }
    });

         if (contentLength < 0){
         }
         else{
                byte[] data = new byte[512];
                int len = 0;
                try
                {
                    while (-1 != (len = inputStream.read(data)) )
                    {
                        buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                try
                {
                    inputStream.close(); // closing the stream…..
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                res = buffer.toString();     // converting stringbuffer to string…..

                runOnUiThread(new Runnable() {

                @Override
                public void run() {
                   Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
                }
            });
                //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
         }
         return res;
    }

}

希望对你有帮助...

【讨论】:

    【解决方案2】:

    我猜你不能在 onCreate() 中运行这段代码,因为你还没有图片集的 URI。 使用 Get Content Intent 浏览后,您将获得该 URI,因此您必须在此之后执行 HttpUploader。

    一种可能的解决方案是在获取 realPath 后将该 HttpUploader 代码放入 onActivityResult(), 所以之后:

    currImageURI = data.getData();

    编辑:

    // To handle when an image is selected from the browser
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
        // currImageURI is the global variable I’m using to hold the content:
            currImageURI = data.getData();
            System.out.println(“Current image Path is ----->” + 
                           getRealPathFromURI(currImageURI));
            TextView tv_path = (TextView) findViewById(R.id.path);
            tv_path.setText(getRealPathFromURI(currImageURI));
    
            try{
                HttpUploader uploader = new HttpUploader();
                image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();       
            } catch (Exception e) {
               e.printStackTrace();
            }
        }
    }
    }
    

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 2013-12-17
      • 2014-03-24
      • 2011-02-02
      • 2015-03-29
      • 2014-04-19
      • 2011-10-15
      • 2020-11-19
      • 2011-08-31
      相关资源
      最近更新 更多