Uploading Image from android to PHP server

那年仲夏 提交于 2019-11-27 20:19:10

Use below code. It will do the same.

public class UploadImage extends Activity {
    InputStream inputStream;
        @Override
    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("server-link/folder-name/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;
        }
}

PHP Code

<?php
    $base=$_REQUEST['image'];
     $binary=base64_decode($base);
    header('Content-Type: bitmap; charset=utf-8');
    $file = fopen('uploaded_image.jpg', 'wb');
    fwrite($file, $binary);
    fclose($file);
    echo 'Image upload complete!!, Please check your php file directory……';
?>
    public JSONObject getJSONFromUrlPost(String url, String userid,
                String filepath, String status) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            HttpParams httpParams = httpclient.getParams();
            httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 100000);
            try {
                entity.addPart("id",
                        new StringBody(userid, Charset.forName("UTF-8")));
                entity.addPart("sharestatus",
                        new StringBody(status, Charset.forName("UTF-8")));
                entity.addPart("file", new FileBody(new File(filepath)));
                httppost.setEntity(entity);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String response = httpclient.execute(httppost, responseHandler);
                return new JSONObject(response.toString());
            } catch (Exception e) {
                return null;
            }
        }



------------------------------------------------------------------
in main.java  



JSONParser js = new JSONParser();
String url="";// upload file with Server url
            JSONObject data = js.getJSONFromUrlPost(url);
            String response;
            try {
                response = data.getString("Msg");
                if (response.contains("Succesfully upload file")) {
                    JSONObject jsondata = new JSONObject(data.getString("Data"));
                    Fileurl = jsondata.getString("Url");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!