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
Developer
Posts: 144
Registered: ‎08-18-2012
My Device: Blackberry Curve 8520
Accepted Solution

Problem: How to upload file to server

[ Edited ]

I'm a newbie to BB development. I'm having problems uploading file from my BB to server.

Any help would be appreciated..Thanks..

 

Thread Code:

 

class UploadThrd extends Thread
{
String boundary = "*****";
String lineend = "\r\n";
String twoHyphens = "--";
int maxBufferSize = 0;
DataInputStream fileInputStream = null;
public void run()
{
try{
FileConnection fis=(FileConnection)Connector.open("file:///store/home/user/newfile.txt");
CreateFileScreen.showMsg("File name fetched");
InputStream inputStream = fis.openInputStream();

ByteArrayOutputStream bos=new ByteArrayOutputStream();
int buffersize=(int) fis.fileSize();
byte[] buffer=new byte[buffersize];
int length=0;
while((length=inputStream.read(buffer))!=-1)
{
bos.write(buffer,0,length);
}
byte[] b=bos.toByteArray();
CreateFileScreen.showMsg("File copied..");


ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://www.myserver.net/z/upload.php");
if (connDesc != null)
{
HttpConnection conn;
conn = (HttpConnection)connDesc.getConnection();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("http Connected..");
}
});
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
conn.setRequestProperty( "Connection", "Keep-Alive" );
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("HTTPConnection SET..checking Response Code..");
}
});
conn.setRequestProperty( "Content-Length", Long.toString(b.length) );
// end set


if(conn.getResponseCode()== HttpConnection.HTTP_OK)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("Response Code : HTTP_OK!");
}
});
OutputStream os = conn.openOutputStream();
//Write byte
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("Writing Bytes..");
}
});

String ct="Content-Type: multipart/form-data;boundary="+boundary;
os.write("Content-Disposition: form-data; name=\"source\"".getBytes());
os.write(lineend.getBytes());
os.write(lineend.getBytes());
os.write("blackberry".getBytes());
os.write(lineend.getBytes());

os.write(twoHyphens.getBytes());
os.write(boundary.getBytes());
os.write(lineend.getBytes());

String filename="z\newfile.txt";
os.write("Content-Disposition: form-data; name=\"Filedata\"; filename=\"".getBytes());
os.write(filename.getBytes());
os.write("\"".getBytes());
os.write(lineend.getBytes());

os.write(ct.getBytes());
os.write(lineend.getBytes());
os.write(lineend.getBytes());

os.write(b, 0, b.length);

os.write(lineend.getBytes());

os.write(twoHyphens.getBytes());
os.write(boundary.getBytes());
os.write(twoHyphens.getBytes());
os.write(lineend.getBytes());
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("File uploaded!");
}
});
os.flush();
os.close();
}
else
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("No Connection");
}
});
conn.close();
}

}
catch (Exception e) {
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("====Exception!");
}
});
}
}
}

 

 

App Class:

 

public class CreateFileApp extends UiApplication
{
/**
* Entry point for application
* @param args Command line arguments (not used)
*/
public static void main(String[] args)
{
try
{
FileConnection fc = (FileConnection)Connector.open("file:///store/home/user/newfile.txt");
if (!fc.exists())
{
fc.create(); // create the file if it doesn't exist
}
OutputStream outStream = fc.openOutputStream();
outStream.write("test content".getBytes());
outStream.close();
fc.close();
CreateFileScreen.showMsg("I'm Going to upload file..");
UploadThrd thread=new UploadThrd();
thread.start();
}
catch (IOException e)
{
System.out.println("====IOException: "+e.getMessage() );
}
catch(Exception e1)
{
System.out.println("====Exception: "+e1.getMessage() );
}
// Create a new instance of the application and make the currently
// running thread the application's event dispatch thread.
CreateFileApp theApp = new CreateFileApp();
theApp.enterEventDispatcher();
}

/**
* Creates a new CreateFileApp object
*/
public CreateFileApp()
{
// Push a screen onto the UI stack for rendering.
pushScreen(CreateFileScreen.cfs);
}
}

 

 

Screen class:

 

public final class CreateFileScreen extends MainScreen
{
/**
* Creates a new CreateFileScreen object
*/
public static CreateFileScreen cfs=new CreateFileScreen();
public CreateFileScreen()
{
// Set the displayed title of the screen
setTitle("Create File");
}
public static void showMsg(String msg)
{
LabelField lbl=new LabelField(msg);
cfs.add(lbl);
}
}

 

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

Re: Problem: How to upload file to server

[ Edited ]

Welcome t the forums.

 

Have a look at the HTTP Post example that you will find in the API documentation for HttpConnection.

 

You should do the output I/O before you establish the connection.  Getting the response code establlishes the connection so you need to add the output bytes before you do that. 

Developer
Posts: 144
Registered: ‎08-18-2012
My Device: Blackberry Curve 8520

Re: Problem: How to upload file to server

Thanks you for your quick reponse..I've updated my code as you said but its still not working..please can you check what I'm doing wrong?..

Thanks..

 

 

class UploadThrd extends Thread
{
String boundary = "*****";
String lineend = "\r\n";
String twoHyphens = "--";
int maxBufferSize = 0;
DataInputStream fileInputStream = null;
public void run()
{
try{
FileConnection fis=(FileConnection)Connector.open("file:///store/home/user/newfile.txt");
CreateFileScreen.showMsg("File name fetched");
InputStream inputStream = fis.openInputStream();

ByteArrayOutputStream bos=new ByteArrayOutputStream();
int buffersize=(int) fis.fileSize();
byte[] buffer=new byte[buffersize];
int length=0;
while((length=inputStream.read(buffer))!=-1)
{
bos.write(buffer,0,length);
}
byte[] b=bos.toByteArray();
CreateFileScreen.showMsg("File copied..");
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://www.myserver.net/z/upload.php");
if (connDesc != null)
{
HttpConnection conn;
conn = (HttpConnection)connDesc.getConnection();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("http Connected..");
}
});
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
conn.setRequestProperty( "Connection", "Keep-Alive" );
conn.setRequestProperty( "Content-Length", Long.toString(b.length) );
// end set

OutputStream os = conn.openOutputStream();
//Write byte
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("Writing Bytes..");
}
});
String ct="Content-Type: multipart/form-data;boundary="+boundary;
String cl="Content-Length: "+Long.toString(b.length);
os.write(twoHyphens.getBytes());
os.write(boundary.getBytes());
os.write(lineend.getBytes());

os.write("Connection: Keep-Alive".getBytes());
os.write(lineend.getBytes());
os.write(lineend.getBytes());

os.write(cl.getBytes());
os.write(lineend.getBytes());
os.write(lineend.getBytes());

os.write(ct.getBytes());
os.write(lineend.getBytes());
os.write(lineend.getBytes());

os.write(b, 0, b.length);

os.write(lineend.getBytes());

os.write(twoHyphens.getBytes());
os.write(boundary.getBytes());
os.write(twoHyphens.getBytes());
os.write(lineend.getBytes());
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("HTTPConnection SET..checking Response Code..");
}
});
if(conn.getResponseCode()== HttpConnection.HTTP_OK)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("Response Code : HTTP_OK!");
}
});

UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("File uploaded!");
}
});
os.flush();
os.close();
}
else
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("No Connection");
}
});
conn.close();
}
}
catch (Exception e) {
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run() {
Dialog.alert("====Exception : ");
}
});
}
}
}

 

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

Re: Problem: How to upload file to server

"please can you check what I'm doing wrong"

 

Sorry, for this investigation you are gong to have to do the leg work.

 

The first point to make is "its still not working" is not a very helpful description of the problem you are having.  if you took your car into the garage and said "its not working" to the mechanic, would the mechanic have any idea where to start?

 

So debug this code, tell us which step it gets to, and what happens.  Exception, http response code etc. 

 

And you need to investigate the Server - does the server actually see any requests?  If not, what connection method are you using:

http://supportforums.blackberry.com/t5/Java-Development/Networking-Transports-II/ta-p/446742

http://supportforums.blackberry.com/t5/Java-Development/Different-ways-to-make-an-HTTP-or-socket-con...

 

Finally networking issues are fairly common, search the forum for help too. 

 

Hopefully all of this will help you progress.  if not, come back to us!

Developer
Posts: 172
Registered: ‎01-17-2011
My Device: 9500 series

Re: Problem: How to upload file to server

[ Edited ]

Hello Welcome to the Forums !

You need to use boundry Property tto allow multi part uploading  on server from Your BB using Post.

There is a good Example In nokia Forums , Where you can mode it accordint to Your parameters & file Type.

 

http://www.developer.nokia.com/Community/Wiki/HTTP_Post_multipart_file_upload_in_Java_ME

 

Thanks

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

Re: Problem: How to upload file to server

The previous poster makes a good point, I had not even spotted that your were using multi-part uploading.

 

But there is a bug in your code anyway.  You need to close and flush the output stream before you make the connection, i.e. before you get the response code.  So move these lines:

os.flush();
os.close();

to before this:

if(conn.getResponseCode()== HttpConnection.HTTP_OK)

 

Also you might find that Status is a better control to use than Dialog for information messages because it will automatically remove itself. 

 

But I wonder if the problem you are really having is a connection problem, for example, you might need to start the MDS Simualtor when testing on a Smartphone SImualtor.  Check out the video and KB article for more. 

New Developer
Posts: 21
Registered: ‎07-26-2012
My Device: 9790

Re: Problem: How to upload file to server

Follow the rfc for multi part uploading  http://www.ietf.org/rfc/rfc1867.txt .

 

And in setRequestProperty add some more info like:

setRequestProperty(
HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
"ISO-8859-1,utf-8;q=0.7,*;q=0.7");

 

setRequestProperty(
HttpProtocolConstants.HEADER_CONTENT_LENGTH,totalSize);

 

Thanks,

Ajay

 

Developer
Posts: 144
Registered: ‎08-18-2012
My Device: Blackberry Curve 8520

Re: Problem: How to upload file to server

[ Edited ]

Thank you all for your reponses..

I have done all the above..and here's my code:

 

FetchFile.java:

public class FetchFile extends Thread{

public void run(){
byte[] response=null;
try{
byte[] fileBytes = getFileBytes();
PostFile req = new PostFile(
"http://www.myserver.net/z/upload.php;deviceside=true",
"uploadedfile", "newfile.txt", "text/plain", fileBytes
);
response = req.send(fileBytes);
}
catch(Exception e){
System.out.println("====Exception : "+e.getMessage());
}
System.out.println("Server Response : "+response);
synchronized(Application.getEventLock()) {
CreateFileScreen.showMsg("Server Response : "+response);
}
}

public static byte[] getFileBytes(){
byte[] b=null;
try{
FileConnection fis=(FileConnection)Connector.open("file:///store/home/user/newfile.txt");
synchronized(Application.getEventLock()) {
CreateFileScreen.showMsg("File name fetched");
}
InputStream inputStream = fis.openInputStream();
ByteArrayOutputStream bos=new ByteArrayOutputStream();
int buffersize=(int) fis.fileSize();
byte[] buffer=new byte[buffersize];
int length=0;
while((length=inputStream.read(buffer))!=-1)
{
bos.write(buffer,0,length);
}
b=bos.toByteArray();
synchronized(Application.getEventLock()) {
CreateFileScreen.showMsg("File copied..");
}
}
catch(IOException e){
synchronized(Application.getEventLock()) {
CreateFileScreen.showMsg("====Exception : "+e.getMessage());
}
}
return b;
}
}


PostFile.java:

public class PostFile
{
static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
byte[] postBytes = null;
String url = null;

public PostFile(String url, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
{
this.url = url;
String boundary = getBoundaryString();
String boundaryMessage = getBoundaryMessage(boundary, 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, String fileField, String fileName, String fileType)
{
StringBuffer res = new StringBuffer("--").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(byte[] fileBytes) 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);
hc.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH ,Integer.toString(fileBytes.length));
OutputStream dout = hc.openOutputStream();
dout.write(postBytes);
dout.close();
int ch;
is = hc.openInputStream();
if(hc.getResponseCode()== HttpConnection.HTTP_OK)
{
synchronized(Application.getEventLock()) {
CreateFileScreen.showMsg("Response Code : HTTP_OK!");
}
while ((ch = is.read()) != -1)
{
bos.write(ch);
}
res = bos.toByteArray();
//System.out.println("res loaded..");
}
}
catch(IOException e)
{
e.printStackTrace();
synchronized(Application.getEventLock()) {
CreateFileScreen.showMsg("====IOException : "+e.getMessage());
}
}
catch(Exception e1)
{
e1.printStackTrace();
synchronized(Application.getEventLock()) {
CreateFileScreen.showMsg("====Exception : "+e1.getMessage());
}
}
finally
{
try
{
if(bos != null)
bos.close();

if(is != null)
is.close();

if(hc != null)
hc.close();
}
catch(Exception e2)
{
e2.printStackTrace();
synchronized(Application.getEventLock()) {
CreateFileScreen.showMsg("====Exception : "+e2.getMessage());
}
}
}
return res;
}
}

 

CreateFileApp.java:

public class CreateFileApp extends UiApplication
{
public static void main(String[] args)
{
try
{
FileConnection fc = (FileConnection)Connector.open("file:///store/home/user/newfile.txt");
if (!fc.exists())
{
fc.create(); // create the file if it doesn't exist
}
OutputStream outStream = fc.openOutputStream();
outStream.write("test content".getBytes());
outStream.close();
fc.close();
CreateFileScreen.showMsg("I'm Going to upload file..");
FetchFile thread=new FetchFile();
thread.start();
}
catch (IOException e)
{
System.out.println("====IOException: "+e.getMessage() );
}
catch(Exception e1)
{
System.out.println("====Exception: "+e1.getMessage() );
}
CreateFileApp theApp = new CreateFileApp();
theApp.enterEventDispatcher();
}

 

 

I'm getting the server response as: [B@4321920

Everytime I run my code, the response changes. But I'm still unable to upload my file. Please help.

 

Developer
Posts: 144
Registered: ‎08-18-2012
My Device: Blackberry Curve 8520

Re: Problem: How to upload file to server

PHP Code:

 

<?php

  $target_path  = '/';
  $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
  if(move_uploaded_file($_FILES['filename']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name'])." has been uploaded";
  } else{
    echo "There was an error uploading the file, please try again!";
  }
?>
Developer
Posts: 19,612
Registered: ‎07-14-2008
My Device: Not Specified

Re: Problem: How to upload file to server

This statement:

 

"Server Response : "+response

 

will convert the bytes to a String representation of the Object, which in the case of a byte array, is a String representation of its reference, not the data.  If you want the data of the response you need something like

 

"Server Response : "+new String(response)

or

"Server Response : "+new String(response, "UTF-8")