1

I am trying to send a photo over http to my server. So i convert the image to bytes and then i send it across as a name value pair. Here is my code below for doing so. Now my trouble is the server side, how can i recreate and store the image from the string of bytes recieved

i also am using java servlets

Code on android

ByteArrayOutputStream baos = new ByteArrayOutputStream();
pinnedV.getPhoto().compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();

List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("photo",new String(b)));

HttpClient httpclient = new DefaultHttpClient();  
    HttpPost request = new HttpPost(URL);

    try {
        request.setEntity(new UrlEncodedFormEntity(params));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    ResponseHandler<String> handler = new BasicResponseHandler();  
     try {  
         result = httpclient.execute(request, handler);  
     } catch (ClientProtocolException e) {  
         e.printStackTrace();  
     } catch (IOException e) {  
         e.printStackTrace();  
    }  

Code on server

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String fromClientphoto= request.getParameter("photo");
byte[] b = fromClientphoto.getBytes();

FileOutputStream fos = new FileOutputStream("D:\\img.png");
     fos.write(b);
     fos.close(); 
}

This above code writes a file but it will not open as an image. also is this byte[] b = fromClientphoto.getBytes(); the correct way to convert back to same bytes as on the android phone? any ideas?

Guido
  • 46,642
  • 28
  • 120
  • 174
molleman
  • 2,934
  • 16
  • 61
  • 92

2 Answers2

0

Don't bother with the toolkit image, just write the contents out to a file..

can you post an image to the Servlet outside of android? setup a dummy page that does the same thing through a basic HTML Form, break down the problem into smaller and smaller pieces until you figure out whhich piece is causing the problem...

Dave
  • 867
  • 6
  • 11
  • So the image is converted to bytes and then a string is made from them bytes on the android phone......then server side i call the above to convert from the string to bytes...and then i write it to a file – molleman Jun 10 '11 at 19:00
0

You should not send a file (i.e. image) as a regular name-value parameter from your device and read it with request.getParameter(name);.

Instead:

  • In the Android side, use a MultipartEntity (see other questions). It is already part of httpclient.
  • In the server side, you can find apache-fileupload useful (or other library that can help you to read the multipart content you receive in your servlet)
Community
  • 1
  • 1
Guido
  • 46,642
  • 28
  • 120
  • 174