uploading Pdf file not converting to base64 in android - java

I'm not able to convert pdf file to base64 string but file uploaded successfully when I open pdf file it showing 0kb file size. This same code works for an image but when I try to use to convert for pdf file it is not working. in my code I have created a method called 'NewBase64' in that I'm converting pdf file to base64 can any tell me where I'm gone wrong plz help me.
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
private int PICK_IMAGE_REQUEST = 1;
VolleyAppController volleyAppController;
mydb db;
public static String url = "http://xxx.xxx.x.x:xx/Android_Service.asmx/UploadPDFFile";
int SELECT_MAGAZINE_FILE = 1;
private File myFile;
String encodeFileToBase64Binary = "";
private String NewBase64(String Path) {
String encoded = "";
try {
File file = new File(Path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos = new ObjectOutputStream(bos);
oos.writeObject(file);
bos.close();
oos.close();
byte[] bytearray = bos.toByteArray();
encoded = Base64.encodeToString(bytearray, Base64.DEFAULT);
} catch (Exception ex) {
}
return encoded;
}
private void uploadImage() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String image = null;
image = NewBase64(encodeFileToBase64Binary);
String name1 = name.getText().toString().trim();
Map<String, String> params = new Hashtable<String, String>();
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name1);
return params;
}
};
}

You can convert PDF to base64 using below method
public String NewBase64(File mfile) {
ByteArrayOutputStream output = null;
try {
InputStream inputStream = null;
inputStream = new FileInputStream(mfile.getAbsolutePath());
byte[] buffer = new byte[8192];
int bytesRead;
output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
output64.close();
} catch (IOException e) {
e.printStackTrace();
}
return output.toString();
}

Related

Java - Adding File to the Archive without deleting other files

So I have this code, it pretty much does what it should but my archive ends up broken and it doesn't save the files. Of course I have to achieve these without using FileSystem, no TempFiles or anything.
public static void main(String[] args) throws IOException {
// Path fileName = Paths.get(args[0]);
// String pathZip = args[1];
Path fileName = Paths.get("C:\\Users\\dell\\Desktop\\addfile.txt");
String pathZip = "C:\\Users\\dell\\Desktop\\test.zip";
Map<String, byte[]> zipEntryMap = addFilesInMap(pathZip);
zipEntryMap.forEach((zipEntryName, bytes) -> {
System.out.println(zipEntryName+" "+bytes.toString());
try {
containAndSaveSameFiles(pathZip, bytes, zipEntryName);
} catch (Exception e) {
e.printStackTrace();
}
});
// saveFileInArchive(fileName, pathZip);
}
private static Map<String, byte[]> addFilesInMap(String pathZip) throws IOException {
Map<String, byte[]> zipEntryMap = new HashMap<>();
FileInputStream fileInputStream = new FileInputStream(pathZip);
ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
ZipEntry zipEntry;
while((zipEntry = zipInputStream.getNextEntry())!= null){
byte[] buffer = new byte[1024];
ByteArrayOutputStream builder = new ByteArrayOutputStream();
int end;
while((end = zipInputStream.read(buffer)) > 0){
builder.write(buffer, 0, end);
}
zipEntryMap.put(zipEntry.getName(), builder.toByteArray());
}
return zipEntryMap;
}
private static void containAndSaveSameFiles(String pathZip, byte[] bytes, String zipEntryName) throws Exception{
ByteArrayOutputStream readBytes = new ByteArrayOutputStream();
FileOutputStream fileOutputStream = new FileOutputStream(pathZip);
ZipOutputStream outputStream = new ZipOutputStream(readBytes);
ZipEntry zipEntry2 = new ZipEntry(zipEntryName);
zipEntry2.setSize(bytes.length);
outputStream.putNextEntry(new ZipEntry(zipEntryName));
outputStream.write(bytes);
}
private static void saveFileInArchive(Path fileToBeAdded, String pathToArchive) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(pathToArchive);
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
zipOutputStream.putNextEntry(new ZipEntry("new/"+fileToBeAdded.getFileName()));
Files.copy(fileToBeAdded, zipOutputStream);
zipOutputStream.close();
fileOutputStream.close();
}
I tried a few ways, and look up on the internet but can't find any good answer.
Thank you for help.
Your code is almost correct.
Bug No:1 in containAndSaveSameFiles
Using readBytes instead of fileOutputStream.
Bug No:2 in saveFileInArchive Rewriting OutputStream by reopening it again.
Complete code after review:
public static void main(String[] args) throws IOException {
// Path fileName = Paths.get(args[0]);
// String pathZip = args[1];
Path fileName = Paths.get("C:\\Users\\dell\\Desktop\\addfile.txt");
String pathZip = "C:\\Users\\dell\\Desktop\\test.zip";
Map<String, byte[]> zipEntryMap = addFilesInMap(pathZip);
FileOutputStream fileOutputStream = new FileOutputStream(pathZip);
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
zipEntryMap.forEach((zipEntryName, bytes) -> {
System.out.println(zipEntryName+" "+bytes.toString());
try {
containAndSaveSameFiles(pathZip, bytes, zipEntryName, zipOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
});
saveFileInArchive(fileName, pathZip,zipOutputStream);
zipOutputStream.close();
fileOutputStream.close();
}
private static Map<String, byte[]> addFilesInMap(String pathZip) throws IOException {
Map<String, byte[]> zipEntryMap = new HashMap<>();
FileInputStream fileInputStream = new FileInputStream(pathZip);
ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
ZipEntry zipEntry;
while((zipEntry = zipInputStream.getNextEntry())!= null){
byte[] buffer = new byte[1024];
ByteArrayOutputStream builder = new ByteArrayOutputStream();
int end;
while((end = zipInputStream.read(buffer)) > 0){
builder.write(buffer, 0, end);
}
zipEntryMap.put(zipEntry.getName(), builder.toByteArray());
}
return zipEntryMap;
}
private static void containAndSaveSameFiles(String pathZip, byte[] bytes, String zipEntryName, ZipOutputStream zipOutputStream) throws Exception{
// ByteArrayOutputStream readBytes = new ByteArrayOutputStream();
ZipEntry zipEntry2 = new ZipEntry(zipEntryName);
zipEntry2.setSize(bytes.length);
zipOutputStream.putNextEntry(new ZipEntry(zipEntryName));
zipOutputStream.write(bytes);
}
private static void saveFileInArchive(Path fileToBeAdded, String pathToArchive, ZipOutputStream zipOutputStream) throws IOException, IOException {
zipOutputStream.putNextEntry(new ZipEntry("new/"+fileToBeAdded.getFileName()));
Files.copy(fileToBeAdded, zipOutputStream);
}

Trying to read Text File from Uri Android

I created an android file chooser that returns the uri of a text file. I want to open and read the file and store it's data.My code is:
private void covertFile(Uri data) {
InputStream inputStream = getContentResolver().openInputStream(data);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String myText = "";
int in;
try {
in = inputStream.read();
while (in != -1)
{
byteArrayOutputStream.write(in);
in = inputStream.read();
}
inputStream.close();
myText = byteArrayOutputStream.toString();
}catch (IOException e) {
e.printStackTrace();
}
myTextView.setText(myText);
}
But the line InputStream inputStream = getContentResolver().openInputStream(data); givesjava.Io.FileNotFoundException. How do I resolve this?
EDIT: Issue Resolved
First create file object
String path = data.toString();
File file = new File(path);
Now pass the file object as arg in InputStream
InputStream inputStream = getContentResolver().openInputStream(file);

How can i edit pdf and put it inside zip during stream then download using IText and java?

My use case is this: when the client clicks download on a pdf, I want to edit/write some text on to the pdf using Itext pdf editor, then zip the pdf then let it download, All during the stream. I am aware of memory issue if the pdf is large etc. which won't be an issue since its like 20-50kb. I have the zipping during the stream before downloading working using byte array, now have to make the pdfeditor method also run before zipping, add some text then let the download happen.
Here is my code so far:
public class zipfolder {
public static void main(String[] args) {
try {
System.out.println("opening connection");
URL url = new URL("http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/pdfs/form.pdf");
InputStream in = url.openStream();
// FileOutputStream fos = new FileOutputStream(new
// File("enwiki.png"));
PdfEditor writepdf = new PdfEditor();
writepdf.manipulatePdf(url, dest, "field"); /// where i belive i
/// should execute the
/// editor function ?
File f = new File("test.zip");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
ZipEntry entry = new ZipEntry("newform.pdf");
zos.putNextEntry(entry);
System.out.println("reading from resource and writing to file...");
int length = -1;
byte[] buffer = new byte[1024];// buffer for portion of data from
// connection
while ((length = in.read(buffer)) > -1) {
zos.write(buffer, 0, length);
}
zos.close();
in.close();
System.out.println("File downloaded");
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
}
}
public class PdfEditor {
public String insertFields (String field, String value) {
return field + " " + value;
// System.out.println("does this work :" + field);
}
// public static final String SRC = "src/resources/source.pdf";
// public static final String DEST = "src/resources/Destination.pdf";
//
// public static void main(String[] args) throws DocumentException,
// IOException {
// File file = new File(DEST);
// file.getParentFile().mkdirs();
// }
public String manipulatePdf(URL src, String dest, String field) throws Exception {
System.out.println("test");
try {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
AcroFields form = stamper.getAcroFields();
Item item = form.getFieldItem("Name");
PdfDictionary widget = item.getWidget(0);
PdfArray rect = widget.getAsArray(PdfName.RECT);
rect.set(2, new PdfNumber(rect.getAsNumber(2).floatValue() + 20f));
String value = field;
form.setField("Name", value);
form.setField("Company", value);
stamper.close();
} catch (Exception e) {
System.out.println("Error in manipulate");
System.out.println(e.getMessage());
throw e;
}
return field;
}
}
So playing with ByteArrayOutputStream, finally got it work. passing the input stream to 'manipulatepdf' and returning 'bytedata'.
public ByteArrayOutputStream manipulatePdf(InputStream in, String field) throws Exception {
System.out.println("pdfediter got hit");
ByteArrayOutputStream bytedata = new ByteArrayOutputStream();
try {
PdfReader reader = new PdfReader(in);
PdfStamper stamper = new PdfStamper(reader, bytedata);
AcroFields form = stamper.getAcroFields();
Item item = form.getFieldItem("Name");
PdfDictionary widget = item.getWidget(0);
PdfArray rect = widget.getAsArray(PdfName.RECT);
rect.set(2, new PdfNumber(rect.getAsNumber(2).floatValue() + 20f));
String value = field;
form.setField("Name", value);
form.setField("Company", value);
stamper.close();
} catch (Exception e) {
System.out.println("Error in manipulate");
System.out.println(e.getMessage());
throw e;
}
return bytedata;
}
public String editandzip (String data, String Link) {
try {
System.out.println("opening connection");
URL url = new URL(Link);
InputStream in = url.openStream();
System.out.println("in : "+ url);
//String data = "working ok with main";
PdfEditor writetopdf = new PdfEditor();
ByteArrayOutputStream bao = writetopdf.manipulatePdf(in, data);
byte[] ba = bao.toByteArray();
File f = new File("C:/Users/JayAcer/workspace/test/test.zip");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
ZipEntry entry = new ZipEntry("newform.pdf");
entry.setSize(ba.length);
zos.putNextEntry(entry);
zos.write(ba);
zos.close();
in.close();
System.out.println("File downloaded");
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
return data;
}
}

Display Image in base64 java HttpServer

How to display Base64 string in image on Java com.sun.net.httpserver.HttpServer ?
I run this code:
static class base implements HttpHandler{
#Override
public void handle(HttpExchange he) throws IOException {
byte[] name = Base64.getEncoder().encode(base64String.getBytes());
byte[] decodedString = Base64.getDecoder().decode(new String(name).getBytes("UTF-8"));
String base64String = "BASE64 IMAGE";
Headers headers = he.getResponseHeaders();
headers.add("Content-Type", "image/png");
File file = new File ("1.png");
//System.out.println(file);
FileInputStream fileInputStream = new FileInputStream(file);
InputStream bufferedInputStream = new ByteArrayInputStream(decodedString);
bufferedInputStream.read(decodedString, 0, decodedString.length);
he.sendResponseHeaders(200, decodedString.length);
final OutputStream os = he.getResponseBody();
os.write(decodedString);
os.close();
}
}
But displays a white cube

How to send image file(binary data) using socket.io?

I have trouble to sending data from Android Client to NodeJS Server.
I use Socket.IO-client java library in my client.
But, there is not much information for me.
How can i sending binary data from android client to nodejs server?
You can use Base64 to encode the image:
public void sendImage(String path)
{
JSONObject sendData = new JSONObject();
try{
sendData.put("image", encodeImage(path));
socket.emit("message",sendData);
}catch(JSONException e){
}
}
private String encodeImage(String path)
{
File imagefile = new File(path);
FileInputStream fis = null;
try{
fis = new FileInputStream(imagefile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
//Base64.de
return encImage;
}
So basically you are sending a string to node.js
If you want to receive the image just decode in Base64:
private Bitmap decodeImage(String data)
{
byte[] b = Base64.decode(data,Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(b,0,b.length);
return bmp;
}

Categories