Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Contributor
ducaannalise
Posts: 14
Registered: ‎10-13-2010
My Device: Blackberry 9550 Simultor

Re: HttpConnection, Upload Image!

Thanks for your reply.

 

basically I am trying to pass the image as a byte, however the HTTPConnection never seem to be doing anything. 

 

Also I've tried to follow the following link for further help, however it just don't do anything...http://wiki.forum.nokia.com/index.php/HTTP_Post_multipart_file_upload_in_Java_ME (this link was posted by someone on this forum too)

 

I have added the below code before the instructions given up, it works, however don't open the new HTTPMultipartrequest class

 

 

                byte[] fileBytes = null;
                try{
                FileConnection fconn=(FileConnection)Connector.open(path);
                fileBytes=new byte[(int)fconn.fileSize()];
                DataInputStream dis=fconn.openDataInputStream();
                dis.read(fileBytes);
                Dialog.alert("filebytes" + fileBytes);
                Dialog.alert("DIS REad " +  dis);
                
               
               }catch(Exception e){
                    Dialog.alert("Reading Image."+e);
                }

 While I've tried to apply your code, but i cannot figure out how to pass the file from the app to HttpConnection and to the server - thats where I am trying to ask for more info (I  have been trying for the last week :smileysad:).

 

On the server, I have a php which handles the uploading of the file..as then the webservice takes care of the OCR process (which i am after)

 

Please use plain text.
Developer
mantaker
Posts: 1,477
Registered: ‎12-30-2008
My Device: Torch 9810

Re: HttpConnection, Upload Image!

Is image uploading works alright from a browser?

--
Manimaran Selvan
Co-Founder, Tech Lead,
Equity Markets Research Group
Please use plain text.
Contributor
ducaannalise
Posts: 14
Registered: ‎10-13-2010
My Device: Blackberry 9550 Simultor

Re: HttpConnection, Upload Image!

Yes, image upload works perfectly when done over the html...even if its done from the bberry browser...

 

Do you know of a tutorial which will guide me with what I am doing wrong please?

 

Please use plain text.
Developer
mantaker
Posts: 1,477
Registered: ‎12-30-2008
My Device: Torch 9810

Re: HttpConnection, Upload Image!

If a browser can upload a file for you, so your blackberry application.

 

Well, Now you confirmed that the server-side is quite perfect. All you have to do is, just sniff the packets.. Not some Ethernet level highly sophisticated sniffing.

 

Just httpfox for firefox / httpwatch for Internet Explorer. (I'm looking a similar thing for chrome) is the place you should start with. Understand the request that is going when you do it from a browser. And simulate it in your application.

 

Cheers,

 

 

--
Manimaran Selvan
Co-Founder, Tech Lead,
Equity Markets Research Group
Please use plain text.
Contributor
ducaannalise
Posts: 14
Registered: ‎10-13-2010
My Device: Blackberry 9550 Simultor

Re: HttpConnection, Upload Image!

thanks for your reply. This is my code so far...I am suspecting that the only wrong thing is with the file (php or html) as I am not getting a response back. (When i had a php file, nothing, however when i've applied the html form some html game back in a dialog.

 

Can you kindly look at my code, and notify me where i am in the wrong please...Thanks for your help...

 

Code for button that will save the picture take and open the httpmultipart request

 

 try
                        {       
                                //Create the connection to a file that may or may not exist.
                                FileConnection file = (FileConnection)Connector.open( FILE_NAME + _counter + EXTENSION );


                                //If the file exists, increment the counter until we find
                                //one that hasn't been created yet.
                                while( file.exists() )
                                {
                                        file.close();
                                        ++_counter;
                                        file = (FileConnection)Connector.open( FILE_NAME + _counter + EXTENSION );
                                        
                                }

                                //We know the file doesn't exist yet, so create it.
                                file.create();

                                //Write the image to the file.
                                OutputStream out = file.openOutputStream();
                                
                                out.write(_raw);
                                
                                file.getURL();
                                
                            
                                //Close the connections.
                               // out.close();
                                //file.close();
                               //String path="file:///store/home/user/pictures/IMAGE15.bmp";//.....basically the path to your image.
                               
                                byte[] fileBytes = _raw; //retrieve file bytes with your own code
  
                               	Hashtable params = new Hashtable();
                               	params.put("fname", "annalise");
                               	
                               	 
                               	HttpMultipartRequest req = new HttpMultipartRequest("http://www.senglea-apartments.com/ocr/index.html", params, "upload_field", "IMAGE1.bmp", "image/bmp", fileBytes);
                               	 
                               	byte[] response = req.send();
                               	String res = new String (response);
                               	System.out.println (res);
                               	Dialog.alert(res);
                        
                           
                        }
                        catch(Throwable e)
                        {
                              System.out.println( "ERROR " + e.getClass() + ":  " + e.getMessage() );
                        }

                        //Inform the user where the file has been saved.
                      
                        
                     Dialog.inform( "Saved to " + FILE_NAME + _counter + EXTENSION );  
                        
   		           
                        //Increment the image counter.
                        ++_counter;

                      
                      
                   UiApplication.getUiApplication().popScreen( _imageScreen );
                }

				
        }

 Code for the multipartrequest class

package myAppPackage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
 
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
 
public class HttpMultipartRequest
{
	static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
 
	byte[] postBytes = null;
	String url = null;
 
	public HttpMultipartRequest(String url, Hashtable params, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
	{
		
		
		this.url = url;
 
		String boundary = getBoundaryString();
 
		String boundaryMessage = getBoundaryMessage(boundary, params, fileField, fileName, fileType);
 
		String endBoundary = "\r\n--" + boundary + "--\r\n";
 
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
 
		bos.write(boundaryMessage.getBytes());
 
		bos.write(fileBytes);
 
		bos.write(endBoundary.getBytes());
 
		this.postBytes = bos.toByteArray();
 
		bos.close();
	}
 
	String getBoundaryString()
	{
		return BOUNDARY;
	}
 
	String getBoundaryMessage(String boundary, Hashtable params, String fileField, String fileName, String fileType)
	{
		StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
 
		Enumeration keys = params.keys();
 
		while(keys.hasMoreElements())
		{
			String key = (String)keys.nextElement();
			String value = (String)params.get(key);
 
			res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")    
				.append("\r\n").append(value).append("\r\n")
				.append("--").append(boundary).append("\r\n");
		}
		res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n") 
			.append("Content-Type: ").append(fileType).append("\r\n\r\n");
 
		return res.toString();
	}
 
	public byte[] send() throws Exception
	{
		HttpConnection hc = null;
 
		InputStream is = null;
		
 
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
 
		byte[] res = null;
 
		try
		{
		
			hc = (HttpConnection) Connector.open(url+";interface=wifi");
 
			hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
 
			hc.setRequestMethod(HttpConnection.POST);
 
			OutputStream dout = hc.openOutputStream();
 
			dout.write(postBytes);
 
			dout.close();
 
			int ch;
 
			is = hc.openInputStream();
			//added the below 3 lines 
			
			/**int rc = hc.getResponseCode();
			if (rc != HttpConnection.HTTP_OK)
			                throw new IOException("Error response code: " + rc);
 **/
			while ((ch = is.read()) != -1)
			{
				bos.write(ch);
			}
			res = bos.toByteArray();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(bos != null)
					bos.close();
 
				if(is != null)
					is.close();
 
				if(hc != null)
					hc.close();
			}
			catch(Exception e2)
			{
				e2.printStackTrace();
			}
		}
		return res;
		
	}
}

 

 

 

Please use plain text.
Developer
mantaker
Posts: 1,477
Registered: ‎12-30-2008
My Device: Torch 9810

Re: HttpConnection, Upload Image!

The post request when I do an upload goes to this URL

http://www.senglea-apartments.com/ocr/upload.php

 

First of all, I think you have a good understanding about the coding in blackberry. Install Httpfox, sniff packets and see post data etc to understand how browser is sending your request. and Simulate the same through you code.

 

Cheers,

--
Manimaran Selvan
Co-Founder, Tech Lead,
Equity Markets Research Group
Please use plain text.
Contributor
ducaannalise
Posts: 14
Registered: ‎10-13-2010
My Device: Blackberry 9550 Simultor

Re: HttpConnection, Upload Image!

Thanks thanks thanks for your help!

 

I am trying to fix the errors, you are right, i had a problem in the php (but my mind is all messed up)

 

Do you thinbk which is the best way to upload the file? Via html with php or php text only?

When you said to look at the httpfox, and see how the data passes and simulate this on the blackberry...do you mean the headers and their values? (sorry for my stupidity)

 

The thing is the html file is being read from the server and in the console I can see the following

 

 

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>405 Method Not Allowed</TITLE>
</HEAD><BODY>
<H1>Method Not Allowed</H1>
The requested method POST is not allowed for the URL /ocr/index.html.<P>
<HR>
<ADDRESS>Apache/1.3.33 Server at www.senglea-apartments.com Port 80</ADDRESS>
</BODY></HTML>

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><HTML><HEAD><TITLE>405 Method Not Allowed</TITLE></HEAD><BODY><H1>Method Not Allowed</H1>The requested method POST is not allowed for the URL /ocr/index.html.<P><HR><ADDRESS>Apache/1.3.33 Server at www.senglea-apartments.com Port 80</ADDRESS></BODY></HTML>

 

Please use plain text.
Developer
mantaker
Posts: 1,477
Registered: ‎12-30-2008
My Device: Torch 9810

Re: HttpConnection, Upload Image!

Not essentially all the headers and values. But those which are associated with the image. My bad!httpfox is not good in sniffing the stream. I'm attaching a file that is got when I upload an image named dairy1.jpg in tinypic.com. (Using http watch professional)

 

Those letters that are not understandable in that file are content stream of the image (You can gracefully, disregard that but that place should hold your file stream append)

 

You can use a system lever http sniffer to sniff packets that are getting posted from a blackberry simulator.

 

I'm really sorry, I'm gonna bow out of this thread (I will not be available for next three days, might come back and respond after that!). Please post a new thread so that others can also help you. You can link to this thread as well, so people can get context of what you are talking.


Cheers,

--
Manimaran Selvan
Co-Founder, Tech Lead,
Equity Markets Research Group
Please use plain text.
New Developer
AbdurRahim
Posts: 32
Registered: ‎11-02-2009
My Device: Not Specified

Re: HttpConnection, Upload Image!

[ Edited ]

hi,

 

I use your code with the following changing.

"Web_Application_URL"  to my url. "http://localhost:2000/WebSite1/iconServer.aspx"


Bytes_Of_Image_To_Be_Uploaded
byte[] fileBytes = getImageDataFromName("test.png");


but it not working.

does not come to the service where I am debugging.

 

I am using .net service.

 

Thanks in advance.

 

 

Please use plain text.
Developer
peter_strange
Posts: 19,601
Registered: ‎07-14-2008
My Device: Not Specified

Re: HttpConnection, Upload Image!

[ Edited ]

I would not post to a Solved and very old Thread like this.  If you have a new problem, please start a new Thread.

 

In this case, note that localserver as a URL does not work on the Simulator.  Put your PC's actual IP address.  If that does not help, then please start a new Thread.

 

Just to confirm, I presume you are testing on the SImulator and expecting that it will be able to connect to a Web Server running on the same PC as the Simulator. 

Please use plain text.