-
HTTP Post Image
Hi! I am trying the sample code found [URL="http://wiki.forum.nokia.com/index.php/HTTP_Post_multipart_file_upload_with_J2ME"]here[/URL]. The HttpMultipartRequest class is the same, while the MIDlet being used for testing is as follows:
[code]
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.Hashtable;
import javax.microedition.io.file.FileConnection;
public class PostFile extends MIDlet implements Runnable, CommandListener{
private Form form = null;
private Gauge gauge = null;
private Command exitCommand;
private Command uploadCommand;
public PostFile(){
form = new Form("Upload File");
gauge = new Gauge("Progress:", true, 100, 0);
form.append(gauge);
exitCommand = new Command("Exit", Command.EXIT, 0);
uploadCommand = new Command("Upload", Command.SCREEN, 0);
form.addCommand(exitCommand);
form.addCommand(uploadCommand);
form.setCommandListener(this);
}
public void startApp() {
Display.getDisplay(this).setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
private void progress(int total, int current){
int percent = (int) (100 * ((float)current/(float)total));
gauge.setValue(percent);
}
public void run() {
try {
send();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void send() throws Exception {
byte[] fileBytes = getByteArray(Image.createImage("/image.png")); //retrieve file bytes with your own code
Hashtable params = new Hashtable();
params.put("custom_param", "param_value");
params.put("custom_param2", "param_value2");
HttpMultipartRequest req = new HttpMultipartRequest(
"http://localhost:80/uploadScript.php",
params,
"upload_field", "image.png", "image/png", fileBytes
);
byte[] response = req.send();
}
public void commandAction(javax.microedition.lcdui.Command command, javax.microedition.lcdui.Displayable displayable) {
if(command == exitCommand){
this.notifyDestroyed();
}else if(command == uploadCommand){
new Thread(this).start();
}
}
public byte[] getByteArray(Image image) {
int raw[] = new int[image.getWidth() * image.getHeight()];
image.getRGB(raw, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
byte rawByte[] = new byte[image.getWidth() * image.getHeight() * 4];
int n = 0;
for (int i = 0; i < raw.length; i++) {
int ARGB = raw[i];
int a = (ARGB & 0xff000000) >> 24;
int r = (ARGB & 0xff0000) >> 16;
int g = (ARGB & 0xff00) >> 8;
int b = ARGB & 0xff;
rawByte[n] = (byte) b;
rawByte[n + 1] = (byte) g;
rawByte[n + 2] = (byte) r;
rawByte[n + 3] = (byte) a;
n += 4;
}
System.out.println("raw(int) length is: " + raw.length);
System.out.println("raw(Byte) length is: " + rawByte.length);
raw = null;
return rawByte;
}
}
[/code]
The PHP file is as follows:
[code]
<?php
$filesize = filesize($_FILES['upload_field']['tmp_name']);
echo "The uploaded file size is " . $filesize . " bytes\n";
foreach($_POST as $key => $value)
{
echo "Parameter name: " . $key . ", value: " . $value . "\n";
}
?>
[/code]
When I try to run it, I get the following:
[code]
raw(int) length is: 65536
raw(Byte) length is: 262144
java.io.IOException: error 0 during TCP write
at com.sun.midp.io.j2me.socket.Protocol.writeBytes(Protocol.java:360)
at com.sun.midp.io.BaseOutputStream.write(ConnectionBaseAdapter.java:830)
at java.io.DataOutputStream.write(DataOutputStream.java:90)
at com.sun.midp.io.j2me.http.Protocol.sendRequestBody(Protocol.java:1896)
at com.sun.midp.io.j2me.http.Protocol.sendRequest(Protocol.java:1562)
at com.sun.midp.io.j2me.http.Protocol.writeBytes(Protocol.java:1032)
at com.sun.midp.io.BaseOutputStream.write(ConnectionBaseAdapter.java:830)
at java.io.OutputStream.write(OutputStream.java:58)
at HttpMultipartRequest.send(HttpMultipartRequest.java:109)
at PostFile.send(PostFile.java:91)
at PostFile.run(PostFile.java:71)
[/code]
The file I am using can be downloaded [URL="http://img6.imageshack.us/my.php?image=imagegr9.png"]here[/URL].
Hope you can help me.
Thanks.
-
Re: HTTP Post Image
Hi,
Please check the link below,might be it can help you,
[url]http://discussion.forum.nokia.com/forum/showthread.php?t=69348[/url]
[url]http://forums.sun.com/thread.jspa?threadID=5301899[/url]
[url]http://tomcat.apache.org/connectors-doc/[/url]
hope this can help you,
-
Re: HTTP Post Image
I have checked these, but to no avail. And I am using PHP for the server part, not Tomcat/ Servlet. Well, has anyone been able to use the code given in the Wiki? :S Can you try using the code I've provided?
-
Re: HTTP Post Image
Hi,
I guess no body will be having the time that he can do the code for you and then test the issues...
What exactly you are doing ..you are calling the class found here,with your midlet...
[url]http://wiki.forum.nokia.com/index.php/HTTP_Post_multipart_file_upload_with_J2ME[/url]
Please try to debug the code and check that what can be the reason for the same.Try to print the values you are passing to the HTTP class....are these values null or not...
-
Re: HTTP Post Image
I've been able to make a version I got from SE's site work successfully. :)
[code]
...
private final String FILE = "/image.png";
private final String URL = "http://localhost:80/post.php";
private final String CrLf = "\r\n";
private void httpConn(){
HttpConnection conn = null;
OutputStream os = null;
InputStream is = null;
try{
System.out.println("url:" + URL);
conn = (HttpConnection)Connector.open(URL);
conn.setRequestMethod(HttpConnection.POST);
String postData = "";
InputStream imgIs = getClass().getResourceAsStream(FILE);
byte []imgData = new byte[imgIs.available()];
imgIs.read(imgData);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"" + FILE + "\"" + CrLf;
message1 += "Content-Type: image/png" + CrLf;
message1 += CrLf;
// the image is sent between the messages ni the multipart message.
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--" + CrLf;
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
// might not need to specify the content-length when sending chunked data.
// conn.setRequestProperty("Content-Length", String.valueOf((message1.length() + message2.length() + imgData.length)));
System.out.println("open os");
os = conn.openOutputStream();
System.out.println(message1);
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do{
System.out.println("write:" + index);
if((index+size)>imgData.length){
size = imgData.length - index;
}
os.write(imgData, index, size);
index+=size;
progress(imgData.length, index); // update the progress bar.
}while(index<imgData.length);
System.out.println("written:" + index);
System.out.println(message2);
os.write(message2.getBytes());
os.flush();
System.out.println("open is");
is = conn.openInputStream();
char buff = 512;
int len;
byte []data = new byte[buff];
do{
System.out.println("READ");
len = is.read(data);
if(len > 0){
System.out.println(new String(data, 0, len));
}
}while(len>0);
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("Close connection");
try{
os.close();
}catch(Exception e){}
try{
is.close();
}catch(Exception e){}
try{
conn.close();
}catch(Exception e){}
}
}
...
[/code]
With the post.php file as follows:
[code]
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else {
echo "There was an error, try again!";
}
?>
[/code]
But how do I send data along with the file?
For example I want to send a string, Description, which contains a little description and at the server side, I want to retrieve it using $_POST before doing some processing on it. By using simple HTTP Post, it would have been like that:
[code]
...
try {
http = (HttpConnection)Connector.open(url);
http.setRequestProperty("User-Agent","Profile/MIDP- 1.0 Configuration/CLDC-1.0");
http.setRequestProperty("Content-Language", "en-CA");
http.setRequestProperty("CONTENT-TYPE", "application/x-www-form-urlencoded");
http.setRequestProperty( "Connection", "close" );
http.setRequestMethod(http.POST);
[B]String req = "txt="+part+"\r\n" ;[/B]
http.setRequestProperty("Content-Length", Integer.toString( req.length()));
out = http.openOutputStream();
int rlength = req.length();
for ( int i = 0; i < rlength; i++ )
out.write( req.charAt(i));
in = http.openInputStream();
rc = http.getResponseCode();
int ch;
StringBuffer buff = new StringBuffer();
while ( (ch = in.read())!= -1){
buff.append( (char) ch);
}
form.append(new StringItem("Response: ", buff.toString()));
...
[/code]
In the above, part is the value of 'txt' and at the server-side, we retrieve it by uisng $_POST['txt'].
So, how do I send data as well as a file? This has been implemented in the coding I gave in the first post, but I don't know how to implement it in the current case.
-
Re: HTTP Post Image
[QUOTE=girish3110;560406]So, how do I send data as well as a file? This has been implemented in the coding I gave in the first post, but I don't know how to implement it in the current case.[/QUOTE]
I'm not sure what you are asking... Are you asking how to send more than one data item at a time? If so, that depends entirely on the whatever is receiving the data is willing to understand.
The PHP $_POST variable is very limited in this respect. It is expecting to receive items in the following way:
[code]
name1=value1&name2=value2&name3=value3
[/code]
If one of your values contains any of the special symbols (e.g. &, =, space, etc) then it will be encoded using HTTP... e.g. space will be encoded as %20
It is your responsibility to encode the data you send from the phone correctly (if you're using HTML, the browser does this for you, but you're not using HTML or a browser so you have to do it yourself).
A MUCH better solution is to send (and receive) XML. But even then, if you're sending binary data you will still need to encode it in some way (e.g. base64). You'll have to change your PHP scripts of course to use XML instead of $_POST.
- Mike
NAVTEQ Network for Developers
[I]The community for developing innovative location-based applications[/I]
[url]http://NN4D.com[/url]
-
Re: HTTP Post Image
Yes, I want to send several data...in addition to the picture...
What I want to do is used here:
[url]http://wiki.forum.nokia.com/index.php/HTTP_Post_multipart_file_upload_with_J2ME[/url]
In the above, it is possible to add other parameters... But I don't know how to set it in my code..
-
Re: HTTP Post Image
[QUOTE=girish3110;560439]What I want to do is used here:
[url]http://wiki.forum.nokia.com/index.php/HTTP_Post_multipart_file_upload_with_J2ME[/url]
In the above, it is possible to add other parameters... But I don't know how to set it in my code..[/QUOTE]
So now I'm really confused... if you already have the code, and it does what you want, why can't you make it work? What error messages are you getting? Are you sure you are using the code correctly? If you are sure, how do you know?
I'm not sure that this code really does do what you want, since it will only work with text based data... HTTP Multipart does not handle binary data (like bytes equal to 0 for example) if you're trying to send binary data (like a picture) it surely won't work, except accidentally.
You'll note that the example you point to neatly skips the bit about how you load and encode the data from the picture file - getFileBytes(). Generally, you'd use base64 (at both client and server end of course).
- Mike
NAVTEQ Network for Developers
[I]The community for developing innovative location-based applications[/I]
[url]http://NN4D.com[/url]
-
Re: HTTP Post Image
I've made it work... The picture and text data is sent together... Here is the edited part:
[code]
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"username\"" + CrLf;
message1 += CrLf + "Girish" + CrLf;
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.png\"" + CrLf;
message1 += "Content-Type: image/png" + CrLf;
message1 += CrLf;
[/code]
Together with the picture, which is saved as test.png, the data 'username' is also sent. You can then retrieve the data for the latter with $_POST['username'] .
-
Re: HTTP Post Image
hi .. can you help me please.. i've same problem with you.. i've task from my teacher to make upload image using j2me n php...
this is my error :
java.io.IOException: Persistent connection dropped after first chunk sent, cannot retry
at com.sun.midp.io.j2me.http.Protocol.sendRequest(), bci=100
at com.sun.midp.io.j2me.http.Protocol.writeBytes(), bci=31
at com.sun.midp.io.BaseOutputStream.write(), bci=46
at java.io.OutputStream.write(OutputStream.java:58)
at manager.HttpMultipartRequest.send(HttpMultipartRequest.java:114)
at boundary.frmUpload.actionPerformed(frmUpload.java:188)
at com.sun.lwuit.util.EventDispatcher.fireActionSync(), bci=19
at com.sun.lwuit.util.EventDispatcher.fireActionEvent(EventDispatcher.java:211)
at com.sun.lwuit.Form.actionCommandImpl(Form.java:1220)
at com.sun.lwuit.Form.actionCommandImpl(Form.java:1195)
at com.sun.lwuit.Form$MenuBar.actionPerformed(Form.java:2676)
at com.sun.lwuit.util.EventDispatcher.fireActionSync(), bci=19
at com.sun.lwuit.util.EventDispatcher.fireActionEvent(EventDispatcher.java:211)
at com.sun.lwuit.Button.fireActionEvent(Button.java:274)
at com.sun.lwuit.Button.released(Button.java:295)
at com.sun.lwuit.Form$MenuBar.keyReleased(Form.java:2955)
at com.sun.lwuit.Form.keyReleased(Form.java:1731)
at com.sun.lwuit.Display.handleEvent(Display.java:1232)
at com.sun.lwuit.Display.edtLoopImpl(Display.java:636)
at com.sun.lwuit.Display.mainEDTLoop(Display.java:591)
at com.sun.lwuit.RunnableWrapper.run(RunnableWrapper.java:120)
at java.lang.Thread.run(), bci=11
4
exc : java.lang.NullPointerException: 0
-
Re: HTTP Post Image
girish what SE site you are talking about could you please give me d link of it..?
-
Re: HTTP Post Image
Girish3110 was last here four years ago. Please start a new thread and post your question, I'm sure someone will help you.
Graham.
-
Re: HTTP Post Image
Sony Ericsson Developer World
That page, nowadays Sony Mobile, closed most of its J2ME efforts.
If you search for “4664151417711” and “Ericsson” on the Internet, you get several hits showing the source in total.