Android Java String to Blob - java

I am trying to convert a string to blob like this:
byte[] byteArray = myFile.getBytes("UTF-8");//Better to specify encoding
Blob blobData = null;
blobData.setBytes(1, byteArray);
The string contains my pdf file like this
BufferedReader input = null;
input = new BufferedReader(
new InputStreamReader(openFileInput(myFile)));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line + "\n");
}
String text = buffer.toString();
byte[] byteArray = text.getBytes("UTF-8");
Blob blobData = null;
blobData.setBytes(1, byteArray);
In my PHP-File I retrieve the blob like this
$pdf=$_GET['pdf']
$statement = $conn->prepare("INSERT INTO kunden(kunden_plz, kunden_nachname, kunden_vorname, kunden_adresse, kunden_ort, kunden_email, kunden_pdf) VALUES (?,?,?,?,?,?,?)");
$statement->bind_param("sssssss", $postleitzahl, $firstname,$lastname,$citytext,$address,$e_mail,$pdf );
$statement->execute();
My database is not getting the params

The line myFile.getBytes("UTF-8") doesn't read the file content, but only encodes the file path into byte[].
Check this resource to learn about file IO.

Related

Jave InputStream convert to Base64 String not able to open file

I am using an InputStream that is PDF file that needs to be able to converted to a Base64 string. The Base64 string is not correct format because when I decode the PDF file will not open. Is there a better way to do this?
PDFString = fromStream(is);
String encoded = DatatypeConverter.printBase64Binary(PDFString.getBytes());
public static String fromStream(InputStream in) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append(newLine);
}
return out.toString();
}

How to Decide InputStream Encoding?

My objective is to download an xml feed into an InputStream, then convert it to a String so that if may be used with XmlPullParser.
I convert the InputStream into a String like this:
InputStream input_stream = connection.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(input_stream,"UTF-8"));
while ((line = br.readLine()) != null) {
sb.append(line);
}
Here's the problem, some XML feeds define specific encoding. Take this one for example:
http://voxinox.ch/podcasts/valdo/feed.xml
If I use a default of "UTF-8" encoding some characters from the feed look like a black rhombus shape with a question mark in it. If I use the encoding specified in the xml header it works (iso-8859-1), not a surprise.
The thing is how do I decide what encoding to use before I start reading the input stream which contains encoding specifications? Is there a better way of doing this?
Example how i get encoding from XML inputstream
FileInputStream finput = new FileInputStream(myFile);
String encoding = getInputEncoding(finput);
Log.d("Encoding: ", "> " + encoding);
public String getInputEncoding(FileInputStream finput){
String encoding = "";
if(finput!=null){
try{
BufferedReader myReader = new BufferedReader(new InputStreamReader(finput));
String getline = "";
getline = myReader.readLine();
myReader.close();
Log.d("Line: ", "> " + getline);
String[] separated = getline.split("encoding=\"");
String encoding1 = separated[1];
String[] separated2 = encoding1.split("\"");
encoding = separated2[0];
} catch (Exception e) {
}
}
return encoding;
}

How to read the blob data from servlet request object

There is client and server components, the client is sending the data in more secure way by converting the data in blob using POST method to the server.
Can any suggest me how to convert that blob data to string object in server side(Java).i have tried some code below
Way 1):
==============================
String streamLength = request.getHeader("Content-Length");
int streamIntLength = Integer.parseInt(streamLength);
byte[] bytes = new byte[streamIntLength];
request.getInputStream().read(bytes, 0, bytes.length);
String content = DatatypeConverter.printBase64Binary(bytes);
System.out.println(content);
Output for above code is : some junk data is displaying.
dABlAG0AcABsAGEAdABlAD0AMgAzADUAUgBfAFAAcgBvAHYAaQBkAGUAcgBfA
Way 2) :
======
BufferedReader reader = new BufferedReader(new InputStreamReader(
request.getInputStream()));
StringBuilder sb = new StringBuilder();
for (String line; (line = reader.readLine()) != null;) {
String str = new String(line.getBytes());
System.out.println(str);
}
Please suggest me any one, above both ways are not worked out.
Below code works for me.
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
String streamLength = request.getHeader("Content-Length");
int streamIntLength = Integer.parseInt(streamLength);
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream));
char[] charBuffer = new char[streamIntLength];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
}
String body = stringBuilder.toString();
//System.out.println(body);
byte[] bytes = body.getBytes();
System.out.println(StringUtils.newStringUtf16Le(bytes));
From the first approach, it looks like the data is encoded (possibly in Base64 format). After decoding it, what is the problem you are facing ? If the data is String and then encoded to Base64, you should get the actual string after decoding it. (Assuming platform locales on client and server side are same).
If its a binary data, better you keep it inside a byte stream only. If you anyhow want it to convert to a string, then the first approach looks okay.
If this binary data represents some kind of file, you can get the related information using the HTTP headers and write it to temp location for further use.

How to send local .png to .php file on server using java application?

I have a local .png file that I want to send using POST data to a .php script that will save the data to a .png file on the server. How do I do this? Do I have to encode or something? All I have is a File and a way to POST data.
Here is how I am sending the .png:
public static byte[] imageToByte(File file) throws FileNotFoundException {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
} catch (IOException ex) {
}
byte[] bytes = bos.toByteArray();
return bytes;
}
public static void sendPostData(String url, HashMap<String, String> data)
throws Exception {
URL siteUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
Set keys = data.keySet();
Iterator keyIter = keys.iterator();
String content = "";
for (int i = 0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if (i != 0) {
content += "&";
}
content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
}
System.out.println(content);
out.writeBytes(content);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
The PHP script:
<?
// Config
$uploadBase = "../screenshots/";
$uploadFilename = $_GET['user'] . ".png";
$uploadPath = $uploadBase . $uploadFilename;
// Upload directory
if(!is_dir($uploadBase))
mkdir($uploadBase);
// Grab the data
$incomingData = $_POST['img'];
// Valid data?
if(!$incomingData || !isset($_POST['img']))
die("No input data");
// Write to disk
$fh = fopen($uploadPath, 'w') or die("Error opening file");
fwrite($fh, $incomingData) or die("Error writing to file");
fclose($fh) or die("Error closing file");
echo "Success";
?>
I must admit, I am surprised that you almost get the correct file. Actually, when you send a file using a browser, the form tag has an encoding defined: enctype="multipart/form-data". I donĀ“t know how it works (It is defined in https://www.rfc-editor.org/rfc/rfc2388), but it includes encoding the file (for example, in Base64). Anyhow, you can forget about the internals if you use a http client library like the one from Apache HttpComponents
My minimalistic code works:
$body = file_get_contents('php://input');
$fh = fopen('file.txt', 'w') or die("Error opening fil
e");
fwrite($fh, $body) or die("Error writing to file");
fclose($fh)
curl --upload-file download.txt http://example.com/upload.php
However, set the method to PUT.

how to implement PHP file_get_contents() function in JSP(java)?

In PHP we can use file_get_contents() like this:
<?php
$data = file_get_contents('php://input');
echo file_put_contents("image.jpg", $data);
?>
How can I implement this in Java (JSP)?
Here's a function I created in Java a while back that returns a String of the file contents. Hope it helps.
There might be some issues with \n and \r but it should get you started at least.
// Converts a file to a string
private String fileToString(String filename) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(filename));
StringBuilder builder = new StringBuilder();
String line;
// For every line in the file, append it to the string builder
while((line = reader.readLine()) != null)
{
builder.append(line);
}
reader.close();
return builder.toString();
}
This will read a file from an URL and write it to a local file. Just add try/catch and imports as needed.
byte buf[] = new byte[4096];
URL url = new URL("http://path.to.file");
BufferedInputStream bis = new BufferedInputStream(url.openStream());
FileOutputStream fos = new FileOutputStream(target_filename);
int bytesRead = 0;
while((bytesRead = bis.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);
}
fos.flush();
fos.close();
bis.close();

Categories