简体   繁体   中英

How to send an image from android to servlet and then store it

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?

See this link:

Image transfer to the android from java over sockets

It explains how to use the java class.

It may help you.

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...

You should not send a file (ie 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM