While I am uplodaing multiple images in j2me to servlet, I am able to get first image in servlet but not able get second image. is something wrong in my code? could you please suggest
This is my code.
// For First Image uploading
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"image1\"; filename=\"" + FILE1 + "\"" + CrLf;
message1 += "Content-Type: image/jpeg" + 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)>imgData1.length){
size = imgData1.length - index;
}
os.write(imgData1, index, size);
index+=size;
progress(imgData1.length, index); // update the progress bar.
}while(index<imgData1.length);
// For Second Image uploading
message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"image2\"; filename=\"" + FILE2 + "\"" + CrLf;
message1 += "Content-Type: image/jpeg" + CrLf;
message1 += CrLf;
// the image is sent between the messages ni the multipart message.
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(message1);
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do{
System.out.println("write:" + index);
if((index+size)>imgData2.length){
size = imgData2.length - index;
}
os.write(imgData2, index, size);
index+=size;
progress(imgData2.length, index); // update the progress bar.
}while(index<imgData2.length);
Its working fine If I modify the code as below
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
os = conn.openOutputStream();
os.write(message1.getBytes());
// For First Image uploading
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf; message1 += "Content-Disposition: form-data; name=\"image1\"; filename=\"" + FILE1 + "\"" + CrLf; message1 += "Content-Type: image/jpeg" + CrLf; message1 += CrLf;
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do{
System.out.println("write:" + index);
if((index+size)>imgData1.length){
size = imgData1.length - index;
}
os.write(imgData1, index, size);
index+=size;
progress(imgData1.length, index); // update the progress bar.
}while(index<imgData1.length);
// For Second Image uploading
String message2 = "";
message2 += "-----------------------------4664151417711" + CrLf;
message2 += "Content-Disposition: form-data; name=\"image2\"; filename=\"" + FILE2 + "\"" + CrLf;
message2 += "Content-Type: image/jpeg" + CrLf; message1 += CrLf;
os.write(message2.getBytes());
// SEND THE IMAGE
//int index = 0;
int size = 1024;
do{
System.out.println("write:" + index);
if((index+size)>imgData2.length){
size = imgData2.length - index;
}
os.write(imgData2, index, size);
index+=size;
progress(imgData2.length, index); // update the progress bar.
}while(index<imgData2.length);
String message3 = "\r\n-----------------------------4664151417711--\r\n";
os.write(message3.getBytes());
Related
I have a problem that arduino upload a file in sdcard to MS azure cognitive service, such as use a image file for face identify. I have try use multipart http post to upload, and it is useful for another service but not MS azure.
Does anyone have experience in using "application/octet-stream" to upload a file to Azure server?
my multipart post function show below:
void wifisendfile()
{
//connect to wifi
WiFi.begin(ssid.c_str(), pass.c_str());
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
// wait 0.5 second for connection:
delay(500);
}
Serial.print("Wifi Connected,IP address: ");
Serial.println(WiFi.localIP());
//prepare httpclient
Serial.println("Starting connection to server...");
Serial.println(host);
WiFiClient client;
//start http sending
if (client.connect(host.c_str(), 80))
{
//open file
myFile = SD.open("/pic.jpg");
int filesize=myFile.size();
Serial.print("filesize=");
Serial.println(filesize);
String fileName = myFile.name();
String fileSize = String(myFile.size());
Serial.println("reading file");
if (myFile)
{
String boundary = "CustomizBoundarye----";
String contentType = "image/jpeg";
// post header
String postHeader = "POST " + url + " HTTP/1.1\r\n";
postHeader += "Host: " + host + ":80 \r\n";
postHeader += "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n";
postHeader += "Accept-Charset: utf-8;\r\n";
String keyHeader = "--" + boundary + "\r\n";
keyHeader += "Content-Disposition: form-data; name=\"key\"\r\n\r\n";
String requestHead = "--" + boundary + "\r\n";
requestHead += "Content-Disposition: form-data; name=\"\"; filename=\"" + fileName + "\"\r\n";
requestHead += "Content-Type: " + contentType + "\r\n\r\n";
// post tail
String tail = "\r\n--" + boundary + "--\r\n\r\n";
// content length
int contentLength = keyHeader.length() + requestHead.length() + myFile.size() + tail.length();
postHeader += "Content-Length: " + String(contentLength, DEC) + "\n\n";
// send post header
char charBuf0[postHeader.length() + 1];
postHeader.toCharArray(charBuf0, postHeader.length() + 1);
client.write(charBuf0);
//Serial.print("send post header=");
//Serial.println(charBuf0);
// send key header
char charBufKey[keyHeader.length() + 1];
keyHeader.toCharArray(charBufKey, keyHeader.length() + 1);
client.write(charBufKey);
//Serial.print("send key header=");
//Serial.println(charBufKey);
// send request buffer
char charBuf1[requestHead.length() + 1];
requestHead.toCharArray(charBuf1, requestHead.length() + 1);
client.write(charBuf1);
//Serial.print("send request buffer=");
//Serial.println(charBuf1);
// create buffer
const int bufSize = 2048;
byte clientBuf[bufSize];
int clientCount = 0;
// read myFile until there's nothing else in it:
while (myFile.available())
{
clientBuf[clientCount] = myFile.read();
clientCount++;
if (clientCount > (bufSize - 1))
{
client.write((const uint8_t *)clientBuf, bufSize);
clientCount = 0;
}
}
if (clientCount > 0)
{
client.write((const uint8_t *)clientBuf, clientCount);
//Serial.println("Sent LAST buffer");
}
// send tail
char charBuf3[tail.length() + 1];
tail.toCharArray(charBuf3, tail.length() + 1);
client.write(charBuf3);
//Serial.print(charBuf3);
}
Serial.println("end_request");
}
String lastline;
while(client.connected())
{
while(client.available())
{
String line = client.readStringUntil('\r');
lastline=line;
//Serial.print(line);
if(line.indexOf("{")>0)
{
client.stop();
}
}
}
Serial.println(lastline);
myFile.close();
Serial.println("closing connection");
}
After many days trying, I use sniffer to scan the package data in network. I found any data must be send by https to Azure Service. So that any file upload failed. After using HTTPS, files upload fine and get response from azure server.
Can anyone give me a C# code snippet for this kind of file upload:
POST <BASE-URL>/documents
Content-Type: multipart/form-data; boundary=<BOUNDARY>
Transfer-Encoding: chunked
--<BOUNDARY>
Content-Disposition: form-data; name=“metadata”
Content-Type: application/json
{
“metadata” : {
“document” : {
“filename” : <filename>,
“size” : <filesize>,
“title” : <title>,
“author” : <author>
}
}
}
--<BOUNDARY>
Content-Disposition: form-data; name=“document”; filename=“<filename>”
Content-Type: <mime-type>
<File contents>
--<BOUNDARY>--
Currently I am using method shown below and I am getting status 400:Bad Request:
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc,string accessToken)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = false;
wr.SendChunked = true;
wr.Headers.Add("Authorization", "Bearer " + accessToken);
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[256000];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
//log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
I guess it is the json string part of a post header form-data that gives me the trouble... here it uses namevaluecollection...
Thanx!
I am making a post request on an Arduino device with the Ethernet shield. The server is a Node.js server, and I have handled the post request server-side with the same results both with formaline and formidable. The POST is processed, but it doesn't complete the file transfer.
loadstart: {"time":1339574854222}
"bytesReceived": 178,
"filesCompleted": 0
This is the code that sends the post:
String boundary = "--73249889599006000";
String URL = "/upload";
String contentType = "text/plain";
String fileName = "text.txt";
void sendData(){
String thisFile = "This is not the contents of thisFile";
Serial.println("connecting...");
// If you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
String postHeader = "POST " + URL + " HTTP/1.1\n";
postHeader += "Content-Type: multipart/form-data; boundary=";
postHeader += boundary + "\n";
postHeader += "Host: 192.168.3.78\n";
postHeader += "User-Agent: Arduino\n";
postHeader += "Referer: http://192.168.3.78/upload\n";
String requestHead = "\n--" + boundary + "\n";
requestHead += "Content-Disposition: form-data; name=\"upload\"; filename=\"" + fileName + "\"\n";
requestHead += "Content-Type: " + contentType + "\n\n";
String tail = "\n--" + boundary + "--\n\n";
int contentLength = requestHead.length() + thisFile.length() + tail.length();
postHeader += "Content-Length: " + String(contentLength, DEC) + "\n\n";
char charBuf0[postHeader.length() + 1];
postHeader.toCharArray(charBuf0, postHeader.length() + 1);
client.write(charBuf0);
char charBuf1[requestHead.length() + 1];
postHeader.toCharArray(charBuf1, requestHead.length() + 1);
client.write(charBuf1);
char charBuf2[thisFile.length() + 1];
postHeader.toCharArray(charBuf2, thisFile.length() + 1);
client.write(charBuf2);
char charBuf3[tail.length() + 1];
postHeader.toCharArray(charBuf3, tail.length() + 1);
client.write(charBuf3);
}
Line endings and a few other tweaks sorted it. Here is the updated code that works well with formaline.
String boundary = "--73249889599006000";
String URL = "/upload";
String contentType = "text/plain";
String fileName = "text.txt";
void sendData(){
String thisFile = "This is not the contents of thisFile\r\n\r\n";
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
String postHeader = "POST " + url + " HTTP/1.1\r\n";
postHeader += "Content-Type: multipart/form-data; boundary=";
postHeader += boundary + "\r\n";
postHeader += "Host: 192.168.3.18\r\n";
postHeader += "User-Agent: Arduino\r\n";
postHeader += "Referer: http://192.168.3.18/upload\r\n";
String requestHead = "--" + boundary + "\r\n";
requestHead += "Content-Disposition: form-data; name=\"upload\"; filename=\"" + fileName + "\"\r\n";
requestHead += "Content-Type: " + contentType + "\r\n\r\n";
String tail = "--" + boundary + "--\r\n\r\n";
int contentLength = requestHead.length() + thisFile.length() + tail.length();
postHeader += "Content-Length: " + String(contentLength, DEC) + "\n\n";
Serial.print("Content-Length: ");
Serial.println(String(contentLength, DEC));
char charBuf0[postHeader.length() + 1];
postHeader.toCharArray(charBuf0, postHeader.length() + 1);
client.write(charBuf0);
Serial.print(charBuf0);
char charBuf1[requestHead.length() + 1];
requestHead.toCharArray(charBuf1, requestHead.length() + 1);
client.write(charBuf1);
char charBuf2[thisFile.length() + 1];
thisFile.toCharArray(charBuf2, thisFile.length() + 1);
client.write(charBuf2);
Serial.print(charBuf2);
char charBuf3[tail.length() + 1];
tail.toCharArray(charBuf3, tail.length() + 1);
client.write(charBuf3);
Serial.print(charBuf3);
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed");
}
}
I am trying to read a 2mb file into a memory and then send that file to web server. But I am getting out of memory exception.
FileConnection fileConn = (FileConnection)Connector.open("file:///" + pictureURI.getString(), Connector.READ);
InputStream fis = fileConn.openInputStream();
long overallSize = fileConn.fileSize();
int chunkSize = 2048;
int length = 0;
while (length < overallSize)
{
byte[] data = new byte[chunkSize];
int readAmount = fis.read(data, 0, chunkSize);
byte[] newImageData = new byte[rawImage.length + chunkSize];
System.arraycopy(rawImage, 0, newImageData, 0, length);
System.arraycopy(data, 0, newImageData, length, readAmount);
rawImage = newImageData;
length += readAmount;
}
fis.close();
fileConn.close();
500kb files are uploading. What could be the reason? Please shed a light on this.
I tried this also in loop but no use, System.gc();
[EDIT]
https://stackoverflow.com/users/45668/malcolm has put me on right track. Now I struck here
this.progress = progress;
HttpConnection conn = null;
OutputStream os = null;
InputStream s = null;
StringBuffer responseString = new StringBuffer();
try
{
System.out.println(System.getProperty("HTTPClient.dontChunkRequests"));
conn = (HttpConnection)Connector.open(url);
//conn.setRequestProperty("User-Agent", "Profile/MIDP-2.1 Configuration/CLDC-1.1");
conn.setRequestMethod(HttpConnection.POST);
// The messages
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
conn.setRequestProperty("Content-Length", "355");
os = conn.openOutputStream();
System.out.println("file name at upload " + fileName);
String message1 = "";
message1 += "-----------------------------4664151417711\r\n";
message1 += "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n";
message1 += "Content-Type: image/gif\r\n";
message1 += "\r\n";
os.write(message1.getBytes());
System.gc();
// Send the image
int index = 0;
int size = 2048;
double progdouble;
do
{
progdouble = ((double)index) / ((double)rawImage.length) * 100;
progress.setValue((int)progdouble);
if((index+size) > rawImage.length)
{
size = rawImage.length - index;
}
os.write(rawImage, index, size);
index += size;
System.gc();
} while(index < rawImage.length);
String message2 = "\r\n-----------------------------4664151417711\r\n";
message2 += "Content-Disposition: form-data; name=\"number\"\r\n\r\n";
message2 += this.user_phone_number;
os.write(message2.getBytes());
String message3 = "\r\n-----------------------------4664151417711\r\n";
message3 += "Content-Disposition: form-data; name=\"uuid\"\r\n\r\n";
message3 += this.user_uuid;
os.write(message3.getBytes());
String message4 = "\r\n-----------------------------4664151417711--\r\n";
os.write(message4.getBytes());
os.flush();
os.close();
// Read
s = conn.openInputStream();
int ch, i = 0, maxSize = 16384;
while(((ch = s.read())!= -1 ) & (i++ < maxSize))
{
responseString.append((char) ch);
}
conn.close();
System.out.println("response =>"+responseString.toString());
return responseString.toString();
}
catch (IOException ioe)
{
return ioe.toString();
}
Now its failing here..
[EDIT2]
// algorithm that will read 1024 bytes at a time
byte b[] = new byte[chunkSize];
for (int i = 0; i < overallSize; i += chunkSize) {
if ((i + chunkSize) < overallSize) {
fis.read(b, 0, chunkSize);
} else {
int left = (int)overallSize - i;
fis.read(b, 0, left);
}
// writing into the output stream - ( these lines will cause the "memory leak", without these, it will not happen)
os.write(b);
System.gc();
progdouble = ((double)i) / ((double)overallSize) * 100;
progress.setValue((int)progdouble);
}
os.flush();
Thanks in advance.
You allocate a lot of new arrays along the way, which is totally unnecessary. Each new byte[] line allocates a new array.
You should read into one large array, and you should allocate it once, before the loop. You can easily do this since you know the exact size of the file. The code will look something like this:
FileConnection fileConn;
InputStream is;
try {
fileConn = (FileConnection) Connector.open("file:///" + pictureURI.getString(), Connector.READ);
is = fileConn.openInputStream();
long overallSize = fileConn.fileSize();
if (overallSize > Integer.MAX_VALUE) throw new IllegalArgumentException("File is too large);
byte[] imageData = new byte[(int) overallSize];
int chunkSize = 2048;
int bytesReadTotal = 0;
while (bytesRead < overallSize) {
int bytesRead = is.read(imageData, bytesReadTotal, Math.min(imageData.length - bytesReadTotal, chunkSize));
if (bytesRead == -1) break;
bytesReadTotal += bytesRead;
}
} finally {
if (is != null) is.close();
if (fileConn != null) fileConn.close();
}
Your mobile (Nokia x2-01 specs) is limited to 2Mb of heap space for the whole app. Design your app according to these limitations. 2Mb bytearray in memory at once - no way.
While I am uploading the mobile and application number in multipart from-data from mobile it is hitting the server and data is storing in database.Now I added captured image to it and sent to server it is showing an exception.
org.apache.commons.fileupload.FileUploadBase$UnknownSizeException: the request was rejected because its size is unknown
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:305)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest (ServletFileUpload.java:116)
at org.apache.jsp.photo_jsp._jspService(photo_jsp.java:103)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:384)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process (Http11Protocol.java:634)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)
at java.lang.Thread.run(Unknown Source)
Here I am sending Mobile and application Number and captured image in bytes (imagecapturephoto1). Captured image is storing in view after taking photo.But when we are uploading it is showing exception.
try
{
System.out.println("url:" + serverUrl);
connection = (HttpConnection)Connector.open(serverUrl,Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=*****");
connection.setRequestProperty("User-Agent", "Profile/MIDP-2.1 Configuration/CLDC-1.1");
connection.setRequestProperty("Accept", "application/octet-stream" );
writer = new DataOutputStream(connection.openDataOutputStream());
// writer =new DataOutputStream( conn.openOutputStream());
String name="applicationNumber", name1="mobileNumber",name3="photo",
mimeType="text/plain",mimeType2="image/jpeg";
String value="123456789", value1="9849765432",fileName="applicationphoto.jpeg";
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name + "\"");
writeString(NEWLINE);
if (mimeType != null)
{
writeString("Content-Type: " + mimeType);
writeString(NEWLINE);
}
writeString("Content-Length: " + applicationNumber.length());
writeString(NEWLINE);
writeString(NEWLINE);
// write content
writeString(applicationNumber);
writeString(NEWLINE);
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name1 + "\"");
writeString(NEWLINE);
if (mimeType != null)
{
writeString("Content-Type: " + mimeType);
writeString(NEWLINE);
}
writeString("Content-Length: " + mobileNumber.length());
writeString(NEWLINE);
writeString(NEWLINE);
// write content
writeString(mobileNumber);
writeString(NEWLINE);
//uploading image...........
// write boundary
writeString(PREFIX);
writeString(boundary);
writeString(NEWLINE);
// write content header
writeString("Content-Disposition: form-data; name=\"" + name3
+ "\"; filename=\"" + fileName + "\"");
writeString(NEWLINE);
if (mimeType2 != null)
{
writeString("Content-Type: " + mimeType2);
writeString(NEWLINE);
}
writeString("Content-Length: " + imagecapturephoto1.length);
writeString(NEWLINE);
writeString(NEWLINE);
// write content
// SEND THE IMAGE
int index = 0;
int size = 1024;
do
{
System.out.println("write:" + index);
if((index+size)<=imagecapturephoto1.length)
{
writer.write(imagecapturephoto1, index, size);
}
index+=size;
}while(index<imagecapturephoto1.length);
writeString(NEWLINE);
writeString(PREFIX);
writeString(boundary);
writeString(PREFIX);
writeString(NEWLINE);
writer.flush();
//writer.write("-- ***** -- \r\n".getBytes());
serverResponseMessage = connection.getResponseMessage();
InputStream inputstream = connection.openInputStream();
// retrieve the response from server
int chnumber;
StringBuffer sbuffer =new StringBuffer();
while( ( chnumber= inputstream.read() ) != -1 )
{
sbuffer.append( (char)chnumber );
}
String resonsestring=sbuffer.toString();
int end=resonsestring.length();
int tempstr=resonsestring.indexOf(">");
statusResponse=resonsestring.substring(tempstr+1, end);
statusResponse="SUCCESS";
//outputStream.close();
writer.close();
connection.close();
return serverResponseMessage;
}
catch (Exception ex)
{
//statusResponse="SUCCESS";
ex.printStackTrace();
return null;
}
Please suggest me,How we have to upload image from mobile.I was struck from last 10 days.please suggest me how to solve this issue.
Thanks in advance.
-Teja.
kindly try following code segment, Please ignore lat-lon coding.
private void postImageToServer(String curURL) throws Exception
{
// Open up a http connection with the Web server for both send and receive operations
midlet.get_frmLog().append("HttpConnection Enter");
httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE);
// Set the request method to POST
httpConnection.setRequestMethod(HttpConnection.POST);
// Set the request headers
httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action);
httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName);
//httpConnection.setRequestProperty("lat","22.955804");
//httpConnection.setRequestProperty("lon","72.685876");
//httpConnection.setRequestProperty("lat",LatLonFetcherThread.getLatitude());
//httpConnection.setRequestProperty("lon",LatLonFetcherThread.getLongitude());
/*lat = "23.0172";
lon = "72.3416";*/
if ( midlet.get_choiceGroupGPS().getSelectedIndex() == 0 )
{
lat = LatLonFetcherThread.getLatitude();
lon = LatLonFetcherThread.getLongitude();
}
else if ( midlet.get_choiceGroupGPS().getSelectedIndex() != 0 ) // Added By KALPEN
{
if ( midlet.state == mREPORTER.STATE_READING )
{
double xLat,xLon;
try
{
GpsBt.instance().start();
//while (true)
{
gpsBt = GpsBt.instance();
if ( gpsBt.isConnected() )
{
location = gpsBt.getLocation();
//lat = location.utc;
//lon = location.utc;
lat = (location.latitude + location.northHemi);
lon = (location.longitude + location.eastHemi);
lat = lat.substring(0,lat.length()-1);
lon = lon.substring(0,lon.length()-1);
xLat = Double.parseDouble(lat) / (double)100.00;
xLon = Double.parseDouble(lon) / (double)100.00;
lat = xLat + "";
lon = xLon + "";
lat = lat.substring(0,7);
lon = lon.substring(0,7);
//lat = "23.0172";
//lon = "72.3416";
}
Thread.sleep(100);
}
}
catch ( Exception e ) { lat = "23.0172"; lon = "72.3416"; }
}
}
httpConnection.setRequestProperty("lat",lat); // Modifed by KALPEN
httpConnection.setRequestProperty("lon",lon); // Modifed by KALPEN
//String latlongStr = "Latitude: " + LatLonFetcherThread.getLatitude()
// + "\nLongitude: " + LatLonFetcherThread.getLongitude();
/*String latlongStr = "lat: 22.955804" + "lon: 72.685876";*/
//#style screenAlert
/*Alert latlonAlert = new Alert("LatLon alert" );
latlonAlert.setString(latlongStr);
mREPORTER.display.setCurrent(latlonAlert);*/
if(eventName == null || eventName.equals(""))
eventName = "default";
// all the headers are sending now and connection channel is establising
httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName);
httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID);
httpConnection.setRequestProperty(ConstantCodes.COMPRESSION_MODE_REQUEST_PARAMETER, compressionMode);
midlet.get_frmLog().append("Write on server-->"+imageBytes.length);
DataOutputStream dos = httpConnection.openDataOutputStream();
dos.write(imageBytes);
midlet.threadFlag=true;
}
Above Method works fine with my code, as I am also trying to upload Image to Server.