Downloading file with unicode file name in android? - unicode-string

I have to download a file from a url which contains something like this:
https://www.k4health.org/sites/default/files/প্রসব জনতি ফিস্টুলা চিহ্নিত করার চেকলিস্ট H11.pdf
I tried encoding the filename before forming the URL but it's not working. The file is created in my SD card but with 0 bytes. This is how I tried it:
public String saveResourcesToSDCard(Resource res) {
String filepath = null;
String respath = "/bccp/" + bookID + "/resources/";
StringBuilder sb = new StringBuilder();
try {
sb.append(Constant.RESOURCE_FTP);
sb.append(new String(res.filename.getBytes(),"UTF-8"));
URL url = new URL(sb.toString());
//URL url = new URL(res.res_url);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
if(createDirIfNotExists(respath)){
String filename = new String(res.filename.getBytes(),"UTF-8");
Log.v("Local filename:", " " + filename);
File file = new File(SDCardRoot, filename);
if (file.createNewFile()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.v("Progress:", "DownloadedSize: " + downloadedSize
+ " TotalSize: " + totalSize);
}
fileOutput.close();
if (downloadedSize == totalSize){
filepath = file.getPath();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
restartTask();
} catch (IOException e) {
filepath = null;
restartTask();
e.printStackTrace();
}
Log.v("filepath:", " " + filepath);
return filepath;
}
this is the logcat:
03-16 16:38:25.478: W/System.err(21199): java.net.ProtocolException: Unexpected status line: <html>
03-16 16:38:25.480: W/System.err(21199): at com.android.okhttp.internal.http.RawHeaders.setStatusLine(RawHeaders.java:108)
03-16 16:38:25.480: W/System.err(21199): at com.android.okhttp.internal.http.RawHeaders.fromBytes(RawHeaders.java:308)
03-16 16:38:25.481: W/System.err(21199): at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:135)
03-16 16:38:25.482: W/System.err(21199): at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:644)
03-16 16:38:25.483: W/System.err(21199): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:347)
03-16 16:38:25.483: W/System.err(21199): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
03-16 16:38:25.484: W/System.err(21199): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
03-16 16:38:25.484: W/System.err(21199): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:246)
03-16 16:38:25.486: W/System.err(21199): at com.eatl.bdtoolkits.parsers.xmlparser.downloader.ResourceDownloader.saveResourcesToSDCard(ResourceDownloader.java:68)
03-16 16:38:25.486: W/System.err(21199): at com.eatl.bdtoolkits.parsers.xmlparser.downloader.ResourceDownloader$DownloadResourceTask.doInBackground(ResourceDownloader.java:127)
03-16 16:38:25.487: W/System.err(21199): at com.eatl.bdtoolkits.parsers.xmlparser.downloader.ResourceDownloader$DownloadResourceTask.doInBackground(ResourceDownloader.java:1)
03-16 16:38:25.487: W/System.err(21199): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-16 16:38:25.488: W/System.err(21199): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-16 16:38:25.489: W/System.err(21199): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-16 16:38:25.490: W/System.err(21199): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-16 16:38:25.491: W/System.err(21199): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-16 16:38:25.491: W/System.err(21199): at java.lang.Thread.run(Thread.java:841)
What am I missing?

https://www.k4health.org/sites/default/files/প্রসব জনতি ফিস্টুলা চিহ্নিত করার চেকলিস্ট H11.pdf
This isn't a URI. It's nearly an IRI, which can contain non-ASCII characters, but not quite because it has spaces in which are invalid for both URI and IRI.
You need to URL-encode the filename (using the UTF-8 encoding for non-ASCII characters as specified by IRI)
String encoded_name = URLEncoder.encode("প্রসব জনতি ফিস্টুলা চিহ্নিত করার চেকলিস্ট H11.pdf", "utf-8")
.replaceAll("\\+", "%20")
String url = "https://www.k4health.org/sites/default/files/" + encoded_name;
ending up with the valid URI:
https://www.k4health.org/sites/default/files/%E0%A6%AA%E0%A7%8D%E0%A6%B0%E0%A6%B8%E0%A6%AC%20%E0%A6%9C%E0%A6%A8%E0%A6%A4%E0%A6%BF%20%E0%A6%AB%E0%A6%BF%E0%A6%B8%E0%A7%8D%E0%A6%9F%E0%A7%81%E0%A6%B2%E0%A6%BE%20%E0%A6%9A%E0%A6%BF%E0%A6%B9%E0%A7%8D%E0%A6%A8%E0%A6%BF%E0%A6%A4%20%E0%A6%95%E0%A6%B0%E0%A6%BE%E0%A6%B0%20%E0%A6%9A%E0%A7%87%E0%A6%95%E0%A6%B2%E0%A6%BF%E0%A6%B8%E0%A7%8D%E0%A6%9F%20H11.pdf
(Note the replacement of + with %20 is necessary because Java's URLEncoder is actually an encoder for HTML forms in URL query strings, where + is preferred for spaces. This doesn't work with paths where you need the unambiguous %20.)

I've got the solution by doing this:
public String saveResourcesToSDCard(Resource res) {
String filepath = null;
String respath = "/bccp/" + bookID + "/resources/";
StringBuilder sb = new StringBuilder();
try {
sb.append(Constant.RESOURCE_FTP);
String resfile = URLEncoder.encode(res.filename, "utf-8");
String newfile = StringUtils.replace(resfile, "+", "%20");
sb.append(newfile);
Log.i("URL:", " " + sb.toString());
URL url = new URL(sb.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
if(createDirIfNotExists(respath)){
String filename = res.filename;
Log.i("Local filename:", " " + filename);
Log.i("URL:", " " + sb.toString());
File file = new File(SDCardRoot, filename);
if (file.createNewFile()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.v("Progress:", "DownloadedSize: " + downloadedSize
+ " TotalSize: " + totalSize);
}
fileOutput.close();
if (downloadedSize == totalSize){
filepath = file.getPath();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
//restartTask();
} catch (IOException e) {
filepath = null;
//restartTask();
e.printStackTrace();
}
Log.v("filepath:", " " + filepath);
return filepath;
}

Related

How to copy media (videos) from app sandbox storage to DCIM dir

I am downloading videos from my server in the application sandbox storage, at this path:
final String filePath = this.getExternalFilesDir("videos") + "/" + name + ".mp4";
Now, I want to copy some specific files from the path above to another folder in DCIM so users can discover the videos in the gallery.
I am able to create that file, but I don't understand how to copy and move the file.
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "MyFolder");
if (!dir.exists()) {
boolean rv = dir.mkdir();
Log.d(TAG, "Folder creation " + ( rv ? "success" : "failed"));
}
Can anyone help?
Solved it using standard Java IO stream.
String inputFile = "/" + name + ".mp4";
String inputPath = this.getExternalFilesDir("videos") + "";
String outputPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "MyFolder") + "";
private void copyFile(String inputFile, String inputPath, String outputPath) {
try {
File dir = new File(outputPath);
if (!dir.exists()) {
if (!dir.mkdirs()) {
return;
}
}
try (InputStream inputStream = new FileInputStream(inputPath + inputFile)) {
try (OutputStream outputStream = new FileOutputStream(outputPath + inputFile)) {
File source = new File(inputPath + inputFile);
byte[] buffer = new byte[1024];
int read;
long length = source.length();
long total = 0;
while ((read = inputStream.read(buffer)) != -1) {
total += read;
int progress = (int) ((total * 100) / length);
if (progress == 100) {
Toast.makeText(VideoActivity.this, "Completed", Toast.LENGTH_SHORT).show();
}
outputStream.write(buffer, 0, read);
}
}
}
} catch (Exception e) {
FirebaseCrashlytics.getInstance().recordException(e);
}
}

Exception on downloading pdf from envelope

When i run this code.The Content is not allowed in prolog is coming.What is wroung in my code.
Here is code.
import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
public class GetEnvelopeDoc
{
// Enter your info:
static String username = "*****";
static String password = "*****";
static String integratorKey = "******";
static String envelopeId = "**************";
static String envelopeUri = "/envelopes/" + envelopeId;
public static void main(String[] args) throws Exception
{
String url = "https://demo.docusign.net/restapi/v2/login_information";
String baseURL = ""; // we will retrieve this
String accountId = ""; // will retrieve
String authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + username + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" +
"</DocuSignCredentials>";
//
// STEP 1 - Login
//
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Accept", "application/xml");
int statusValue = conn.getResponseCode(); // side-effect of this call is to fire the request off
if( statusValue != 200 ) // 200 = OK
{
System.out.print("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// we use xPath to get the baseUrl and accountId from the XML response body
BufferedReader br = new BufferedReader(new InputStreamReader( conn.getInputStream() ));
StringBuilder responseText = new StringBuilder(); String line = null;
while ( (line = br.readLine()) != null)
responseText.append(line);
String token1 = "//*[1]/*[local-name()='baseUrl']";
String token2 = "//*[1]/*[local-name()='accountId']";
XPath xPath = XPathFactory.newInstance().newXPath();
baseURL = xPath.evaluate(token1, new InputSource(new StringReader(responseText.toString())));
accountId = xPath.evaluate(token2, new InputSource(new StringReader(responseText.toString())));
//--- display results
System.out.println("baseUrl = " + baseURL + "\naccountId = " + accountId);
//
// STEP 2 - Get Info on Envelope's Document(s)
//
> conn = (HttpURLConnection)new URL(baseURL + envelopeUri +
> "/documents/combined").openConnection();
> conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
> conn.setRequestProperty("Content-Type", "application/json");
> conn.setRequestProperty("Accept", "application/pdf");
> statusValue = conn.getResponseCode(); // triggers the request
if( statusValue != 200 )
{
System.out.println("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// Read the response
InputStreamReader isr = new InputStreamReader(new DataInputStream( conn.getInputStream() ));
System.out.println(isr.toString());
br = new BufferedReader(isr);
StringBuilder response = new StringBuilder();
while ( (line = br.readLine()) != null)
response.append(line);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//*[1]/*[local-name()='envelopeDocument']");
Object result = expr.evaluate(new InputSource(new StringReader(response.toString())), XPathConstants.NODESET);
//--- display results
System.out.println("\nDocument List -->");
int cnt = -1;
NodeList documents = (NodeList) result;
String[] docURIs = new String[documents.getLength()];
for (int i = 0; i < documents.getLength(); i++)
{
Node node = documents.item( i );
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
NodeList docNodes = node.getChildNodes();
for (int j = 0; j < docNodes.getLength(); j++)
{
if( docNodes.item(j).getLocalName().equals("documentId"))
System.out.print("documentId: " + docNodes.item(j).getTextContent());
if( docNodes.item(j).getLocalName().equals("name"))
System.out.print(", name: " + docNodes.item(j).getTextContent());
if( docNodes.item(j).getLocalName().equals("uri"))
{
docURIs[++cnt] = docNodes.item(j).getTextContent(); // store the uris for later
System.out.print(", uri: " + docURIs[cnt]);
}
}
System.out.println();
}
}
//
// STEP 3 - Download the document(s)
//
for( int i = 0; i < docURIs.length; i++)
{
// append document uri to url for each document
conn = (HttpURLConnection)new URL(baseURL + docURIs[i]).openConnection();
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
statusValue = conn.getResponseCode();
if( statusValue != 200 )
{
System.out.println("Error calling webservice, status is: " + statusValue);
System.exit(-1);
}
// Grab the document data and write to a local file
isr = new InputStreamReader( conn.getInputStream() );
br = new BufferedReader(isr);
StringBuilder response2 = new StringBuilder();
while ( (line = br.readLine()) != null)
response2.append(line);
BufferedWriter out = new BufferedWriter(new FileWriter("document_" + i + ".pdf"));
out.write(response2.toString());
out.close();
}
System.out.println("\nDone downloading document(s)!");
}
}
Your question is not very clear, I don't know what you mean when you say "the content is not allowed in prolog", however it looks like you have some extra characters in your code. Was this part a copy-paste error? You have the > symbols in front of each of these lines.
> conn = (HttpURLConnection)new URL(baseURL + envelopeUri +
> "/documents/combined").openConnection();
> conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
> conn.setRequestProperty("Content-Type", "application/json");
> conn.setRequestProperty("Accept", "application/pdf");
> statusValue = conn.getResponseCode(); // triggers the request

(HttpConnection) Connector.open("http://www.google.com"); does not responding

HttpConnection c = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
String request = serverUrl; // + "?loc=" + location.getLat() + "," + location.getLng() + "data=" + message.getString();
try {
c = (HttpConnection) Connector.open("http://www.google.com");
c.setRequestMethod(HttpConnection.GET); //default
is = c.openInputStream(); // transition to connected!
int ch = 0;
for (int ccnt = 0; ccnt < 150; ccnt++) { // get the title.
ch = is.read();
if (ch == -1) {
break;
}
sb.append((char) ch);
return sb.toString();
}
} catch (IOException x) {
x.printStackTrace();
} finally {
try {
is.close();
c.close();
} catch (IOException x) {
x.printStackTrace();
}
}
System.out.println(sb.toString());
return null;
in the above code -- this line
(HttpConnection) Connector.open("http://www.google.com");
does not respond. what can i do to resolve this?
try the following
HttpConnection c = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
String request = serverUrl; // + "?loc=" + location.getLat() + "," + location.getLng() + "data=" + message.getString();
try {
c = (HttpConnection) Connector.open("http://www.google.com");
c.setRequestMethod(HttpConnection.GET); //default
int status_code=c.getResponseCode();
if(status_code!=HttpConnection.HTTP_OK)
{
//Show the failure message to user
return;
}
//Remaining part is same as your code
In lots of phones, and some simulators, you can only open a connection in another thread. that is to say, if you try to connect in main therad = UI thread it wont work and wont tell you anything. Try simply wrapping your method in a new thread

Export xml data to Excel using OpenXML

The file is downloading an xlsx file but when i tried to open the file it is saying file is corrupted. Here is the code i'm trying to use please let me know if any changes has to be done for the following.
private void button1_Click(object sender, EventArgs e)
{
ArrayList DataNode = new ArrayList();
XmlDocument xmlobj = new XmlDocument();
ArrayList FinalXML = new ArrayList();
XslCompiledTransform xXslt = new XslCompiledTransform();
xmlobj.Load(#"D:\ExcelImport\Input.xml");
xXslt.Load(#"D:\ExcelImport\demoxsl.xslt");
XmlNodeList DN ;
DN = xmlobj.DocumentElement.GetElementsByTagName("Data");
for (int i = 0; i < DN.Count; i++)
{
DataNode.Add("<ShaleDataExport><Data Flag = '" + i + "' >" + DN.Item(i).InnerXml + "</Data></ShaleDataExport>");
}
string ShaleDataExportXML;
int k = 0 ;
while (k < DN.Count)
{
ShaleDataExportXML = DataNode[k].ToString();
XmlDocument xml = new XmlDocument();
xml.LoadXml(ShaleDataExportXML);
StringWriter sw = new StringWriter();
xXslt.Transform(xml, null, sw);
FinalXML.Add(sw);
sw.Close();
k++;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(#"D:\ExcelImport\OutPut\OutPut.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbook = doc.AddWorkbookPart();
string XML;
string WorbookXML;
WorbookXML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""schemas.openxmlformats.org/.../main"" xmlns:r=""schemas.openxmlformats.org/.../relationships""><sheets>";
for (int j = 0; j < DN.Count; j++)
{
WorksheetPart[] sheet = new WorksheetPart[DN.Count];
sheet[j] = workbook.AddNewPart<WorksheetPart>();
string sheetId = workbook.GetIdOfPart(sheet[j]);
XML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""schemas.openxmlformats.org/.../main"" >";
XML += FinalXML[j].ToString() + "</worksheet>";
string SheetXML = XML.ToString();
XmlDocument SXML = new XmlDocument();
SXML.LoadXml(SheetXML);
byte[] byteArray = Encoding.ASCII.GetBytes(SXML.OuterXml);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
WorbookXML += "<sheet name="+ AddPartXml(sheet[j], text) + " sheetId=" + j.ToString() + " r:id=" + sheetId.ToString() + " />";
}
WorbookXML += "</sheets></workbook>";
AddPartXml(workbook, WorbookXML);
doc.Close();
}
}
public string AddPartXml(OpenXmlPart part, string xml)
{
Uri uri = part.Uri;
String[] sheetNames = uri.OriginalString.Split('/');
string sheetName = sheetNames[sheetNames.Length - 1].Split('.')[0];
using (Stream stream = part.GetStream())
{
byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
stream.Write(buffer, 0, buffer.Length);
}
return sheetName;
}
Thanks in advance
Vineet Mangal
private void button1_Click(object sender, EventArgs e)
{
XmlDocument xmlobj = new XmlDocument();
xmlobj.Load(#"C:\Excel Import\\Input.xml");
XslCompiledTransform xXslt = new XslCompiledTransform();
xXslt.Load(#"C:\ExportToexcel\Data.xslt");
StringWriter sw = new StringWriter();
xXslt.Transform(xmlobj, null, sw);
richTextBox2.Text = sw.ToString();
sw.Close();
XmlDocument Xdoc = new XmlDocument();
Xdoc.LoadXml(sw.ToString());
Xdoc.Save(#"c:\temp\output.xml");
StreamReader sr = File.OpenText(#"c:\temp\output.xml");
string strSheetData = sr.ReadToEnd();
ArrayList DataNode = new ArrayList();
ArrayList FinalXML = new ArrayList();
XmlNodeList DN;
DN = xmlobj.DocumentElement.GetElementsByTagName("Data");
for (int i = 0; i < DN.Count; i++)
{
DataNode.Add("<ShaleDataExport><Data Flag = '" + i + "' >" + DN.Item(i).InnerXml + "</Data></ShaleDataExport>");
}
string ShaleDataExportXML;
int k = 0;
while (k < DN.Count)
{
ShaleDataExportXML = DataNode[k].ToString();
XmlDocument xml = new XmlDocument();
xml.LoadXml(ShaleDataExportXML);
StringWriter sw1 = new StringWriter();
xXslt.Transform(xml, null, sw1);
FinalXML.Add(sw1);
sw.Close();
k++;
}
using (SpreadsheetDocument doc = SpreadsheetDocument.Create(#"c:\\temp\\output.xlsx", DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbook1 = doc.AddWorkbookPart();
string XML;
string WorbookXML;
WorbookXML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships""><sheets>";
for (int j = 0; j < DN.Count; j++)
{
WorksheetPart[] sheet = new WorksheetPart[DN.Count];
sheet[j] = workbook1.AddNewPart<WorksheetPart>();
string sheetId = workbook1.GetIdOfPart(sheet[j]);
XML = #"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" >";
XML += FinalXML[j].ToString() + "</worksheet>";
string SheetXML = XML.ToString();
XmlDocument SXML = new XmlDocument();
SXML.LoadXml(SheetXML);
byte[] byteArray = Encoding.ASCII.GetBytes(SXML.OuterXml);
MemoryStream stream = new MemoryStream(byteArray);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
**WorbookXML += "<sheet name=" + "\"sheet" + (j + 1).ToString() + "\" " + " sheetId=\"" + (j + 1).ToString() + "\" r:id=\"" + sheetId.ToString() + "\" />";
AddPartXml(sheet[j], text);**
}
WorbookXML += "</sheets></workbook>";
AddPartXml(workbook1, WorbookXML);
doc.Close();
}
}
public void AddPartXml(OpenXmlPart part, string xml)
{
**using (Stream stream = part.GetStream())
{
byte[] buffer = (new UTF8Encoding()).GetBytes(xml);
stream.Write(buffer, 0, buffer.Length);
}**
}

How to upload image to server in j2me from mobile by multipart/form-data?

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.

Resources