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
Posts: 14
Registered: ‎10-13-2010
My Device: Blackberry 9550 Simultor

HttpConnection - Sending an image to a server (php)

Dear Someone,

 

I have been trying to do this while reading other posts on forums, but to no avail.

 

I have an application that takes a picture (bmp), I would like to send that picture to a server (where I have php code to handle the rest)

 

Non of the code I am using is working...I don't know what the really problem is. I am running a BB simulator  9500.

 

If some one could guide me to what is the best code to use for such use, I would really appreciated it

 

 

Developer
Posts: 4,764
Registered: ‎07-21-2008
My Device: Not Specified

Re: HttpConnection - Sending an image to a server (php)

There is nothing wrong with your approach.

 

However, if you expect anyone to assist, you are going to have to be more specific about what is not working.

 

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

Re: HttpConnection - Sending an image to a server (php)

Thanks for your reply.

 

So basically I've tried to implement following the attached tutorial - http://wiki.forum.nokia.com/index.php/HTTP_Post_multipart_file_upload_in_Java_ME

 

In order to get the image as a byte, I have created the following code:

 

                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);
                }
 //byte[] fileBytes = getBytes(); //retrieve file bytes with your own code
            	 
           
                try{

             
             
               // byte[] fileBytes = getByteArray();
             		
             	Hashtable params = new Hashtable();

 

However, the next try button is not being executed, and when putting it in the same try...catch, a NullPointerException is firing up.

 

I don;t know what is happening, but I seam to be stuck...

 

I have also tried to use the code from other forums, but it seem that I am getting no response whatsoever.

 

Hope this will help more for some one to answer my concerns.

 

Developer
Posts: 92
Registered: ‎01-15-2009
My Device: Blackberry 9550

Re: HttpConnection - Sending an image to a server (php)

 

Hi, i write some code. Please try.

 

HttpConnection conn;

OutputStream out;

 

byte postRequestByte[] = ;//Bitmap bytes

 

//init connection to Server
conn = (HttpConnection) Connector.open(url);// don't forget add suffix to url ";deviceside=true" if direct, or //";interface=wifi" if wifi
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Length", "" + postRequestByte.length);
out = conn.openOutputStream();
out.write(postRequestByte);

 

//check response code from server           

int rc = conn.getResponseCode();
if (rc != HttpConnection.HTTP_OK)
                throw new IOException("Error response code: " + rc);

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

Re: HttpConnection - Sending an image to a server (php)

Thanks for your reply. I have managed to move 1 inch forward, however i still seem to have a problem.

 

I have the following code - this will capture an image, and opens the other class:

 

 

   private class SaveListener implements FieldChangeListener
        {
            /** A byte array representing an image. */
                private byte[] _raw;

                /**
                 * Constructor.
                 * @param raw A byte array representing an image.
                 */
                public SaveListener(byte[] raw)
                {
                        _raw = raw;
                }

                /**
                 * Saves the image as a file in the BlackBerry filesystem.
                 */
                public void fieldChanged(Field field, int context)
                {
                        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();
                             
                               
                                //byte[] fileBytes = getBytes(); //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/upload.php", params, "upload_field", "IMAGE1.bmp", "image/bmp", _raw);
                               	 
                               	byte[] response = req.send();

                        
                           
                        }
                        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 );
                }

				
        }
    

 

This is the class that is handling the above request...

 

 

package myAppPackage;

import java.io.ByteArrayOutputStream;
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;

import net.rim.device.api.ui.component.Dialog;
 
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);
 
			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();
 
			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;
	}
}

 

I also have a simple php code which is handling the above request...however when i try to extend this to upload the file to a tmp file, a null pointer exception is given...do you know what the problem might be? fileByte not being filled maybe from the above code?

 

 

 

<?php
$fname = $_POST['fname'];
 
$filesize = filesize($_FILES['upload_field']['tmp']);
 
echo "The uploaded file size is " . $filesize . " bytes\n";
 
foreach($_POST as $key => $value)
{
	echo "Parameter name: " . $key . ", value: " . $value . "\n";
}
 
?>

 

 

 

 

 

Developer
Posts: 91
Registered: ‎06-21-2011
My Device: Blackberry Torch 9800
My Carrier: developer

Re: HttpConnection - Sending an image to a server (php)

[ Edited ]

Hi dmazgalin.

I have one question about your post.

I want to sendd image to server and server must accept the following ur;

...user/create?email=&firstname=...

but server also can accept image which name must be image1.How post url with image?

Regards,
Arsen
New Contributor
Posts: 3
Registered: ‎03-02-2012
My Device: 9800
My Carrier: blackberry

Re: HttpConnection - Sending an image to a server (php)

I am doing the same but still nothings happening, it doesn't even go to my php page!! some guidance. thnks 

Developer
Posts: 19,636
Registered: ‎07-14-2008
My Device: Not Specified

Re: HttpConnection - Sending an image to a server (php)

Welcome to the forum.

 

Networking is hard, you need to have some basics before you start.  The best place to start is review the networking tutorials and videos you will find if you put 'network' in the Search box (top right).

 

Then there is the coding and the need to get off the Event Thread.  look at the httpDemo code for inspiration on that.

 

Beyond that, if you are still having problems, do search the forum a bit and/or provide us with a bit more details.

 

Good luck. 

New Contributor
Posts: 3
Registered: ‎03-02-2012
My Device: 9800
My Carrier: blackberry

Re: HttpConnection - Sending an image to a server (php)

now it seems to work but it uploads empty .jpg file!!

 

my image reader method and the rest is same as above..

 

private byte[] getImageBytes(String path) throws IOException {
FileConnection fconn = null;
InputStream iStream = null;
byte[] file = null;

try
{
fconn = (FileConnection) Connector.open(path, Connector.READ);
iStream = fconn.openInputStream();

file = IOUtilities.streamToBytes(iStream);

}catch (Exception e) {
Dialog.alert("Error: " + e.getMessage());
}finally{

if(iStream != null )
iStream.close();
if(fconn != null)
fconn.close();
}

return file;
}

 

thanks