0

I'm a newbie with android studio. I want to upload an image to a server without converting it into a base64 string. I don't know how to do this. Here is my code:

//This is my code
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

HttpClient Client = new DefaultHttpClient();
HttpPost Post = new HttpPost("url/uploadphoto.php");

            Log.d("HTTPPSt", "" + Post);
            // Building post parameters
            // key and value pair
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
            nameValuePair.add(new BasicNameValuePair("image", bitmap));

            // Url Encoding the POST parameters
            try {
                Post.setEntity(new UrlEncodedFormEntity(nameValuePair));

            } catch (UnsupportedEncodingException e) {
                // writing error to Log
                e.printStackTrace();
            }
            // Making HTTP Request
            try {
                HttpResponse response = Client.execute(Post);
                StatusLine statusLine=response.getStatusLine();
                // writing response to log
                Log.d("Http Response:", response.toString());
                Log.d("statusline:", ""+statusLine);

            } catch (ClientProtocolException e) {
                // writing exception to log
                e.printStackTrace();
            } catch (IOException e) {
                // writing exception to log
                e.printStackTrace();
            }

I have this problem:

nameValuePair.add(new BasicNameValuePair("image", bitmap));

I can not send the bitmap instead I get an error.

Jonathan Drapeau
  • 2,610
  • 2
  • 26
  • 32
Tachchai
  • 1
  • 2
  • `new HttpPost("url/uploadphoto.php");`. You have to specify the protocoll. So `new HttpPost("http://website.url/uploadphoto.php");` – greenapps Jul 24 '15 at 10:38
  • `new BasicNameValuePair("image", bitmap)`. Tha cannot work for image data. That can only be used for Strings. I advise you to google/serach for uploading images witht POST. Only on stackoverflow you will already find hundreds of threads about this issue. – greenapps Jul 24 '15 at 10:40
  • try using Multipart Entity as given Here: https://vikaskanani.wordpress.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/ – Abdul Mohsin Jul 24 '15 at 10:50
  • possible duplicate of [Uploading Images to Server android](http://stackoverflow.com/questions/20322528/uploading-images-to-server-android) – Abhinav Singh Maurya Jul 24 '15 at 10:59

1 Answers1

0

Instead of writing it yourself, consider using a library.

There are very good networking libraries that can do this, including Retrofit and Volley.

If you look, I'm sure that there are also image handling libraries that include upload and download functionality.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67