Unable to POST large html content to server on Chrome - java

I'm trying to send HTML content through a POST request but it is not getting delivered on the server side using Chrome. While I get the request data in my jsp when using Mozilla.
This works in both browsers when the HTML content is small. I'm generating a PDF with this HTML content using Apache FOP.
var iframe = document.createElement('iframe');
iframe.setAttribute('name','eyeframe');
document.body.appendChild(iframe);
var myform = document.createElement('form');
document.body.appendChild(myform);
myform.setAttribute('action','myJspToRenderHtmlAsPdf.jsp');
myform.setAttribute('method','post');
myform.setAttribute('target','eyeframe');
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "htmlContent");
hiddenField.setAttribute("value", strHTML);
myform.appendChild(hiddenField);
myform.submit();
I am dividing the HTML into chunks and posting them and rejoining them in the jsp. This method of doing it also fails with chrome and ie.

Well inputs in chrome (or maybe whole webkit) has limit of chars - 524288, You can test it by typing in console:
var el = document.createElement("input");
el.maxLength
Why not use simple FormData?
var formData = new FormData();
formData.append("htmlContent", strHTML);
var request = new XMLHttpRequest();
request.open("POST", "myJspToRenderHtmlAsPdf.jsp");
request.send(formData);
Got some time to write simple demo. Server respons is generated PDF:
Download
<script>
var formData = new FormData();
formData.append("htmlContent", 'test');
var request = new XMLHttpRequest();
request.responseType = 'blob';
request.open("POST", "myJspToRenderHtmlAsPdf.jsp");
request.onload = function(event) {
if (request.status == 200) {
var blob = new Blob([request.response], {type: 'application/pdf'});
var url = URL.createObjectURL(blob);
var link = document.querySelector('#test');
link.setAttribute('href', url);
} else {
// Handle error
}
};
request.send(formData, true);
</script>

Related

How to dowload a file (blob) which is Int8Array in Angular

I am trying to download a file in Angular. The file is saved in db as varbinary. Java REST service fetched it as byte[]. I am having it as Int8Array in Angular. However when I download it I beleive it is base64 encoded
const link = document.createElement( 'a' );
link.style.display = 'none';
document.body.appendChild( link );
const blob = new Blob([myFileByteArray], {type: 'text/xlsx'}); //myFile is Int8Array
const objectURL = URL.createObjectURL(blob);
link.href = objectURL;
link.href = URL.createObjectURL(blob);
link.download = this.myfile.name;
link.click();
This is how it is in MSSQL: 0x323032312D30392D323720303 ...
And this is how it is when I download this xlsx and open it: MjAyMS0wOS0yNyAwNzozMDsxMi4wODI7bT
I beleive it is base64 encoded somewhere in that path from sql to browser...I saved it in a SQL like this 'CAST('this is my xslx' AS VARBINARY (MAX)) so I know it should be this text.
The solution was to change a type in Angular from Int8Array to string and then I could use atob() method to decode from base64. I just don't know why is it in base64. Could it be because I use Spring Boot ResponseEntity ...
this.myFile= this.myFileResultSet.result;
let myFileByteArray = this.myFile.myFileBytes //before Int8Array, now String
console.log(myFileByteArray);
let myFileDecoded = atob(myFileByteArray); // must be string not Int8Array to be able to
// convert it from base64
const link = document.createElement( 'a' );
link.style.display = 'none';
document.body.appendChild( link );
const blob = new Blob([myFileDecoded], {type: 'text/csv'});
const objectURL = URL.createObjectURL(blob);
link.href = objectURL;
link.href = URL.createObjectURL(blob);
link.download = this.myFile.name;
link.click();
});

How to convert ByteBuffer to pdf

In my application a pdf report only opens in print preview which allows user to directly print the pdf document. Now i want to automate this to verify the pdf content.
I have got the pdf content through an api which is in base64 [did split to get only data], i tried converting to byte array after decoding but it only prints junk characters.[byte array to string]
Now i have converted this data into ByteBuffer and want this to write in pdf.
ByteBuffer decodedBytes = new BASE64Decoder().decodeBufferToByteBuffer(
new String(base64split2[1].substring(0, base64split2[1].length() - 1))
);
Can someone tell me how do i convert this decodedBytes of ByteBuffer to pdf.
Thanks
byte[] decodedBytes = new BASE64Decoder().decodeBuffer(str);
InputStream targetStream = new ByteArrayInputStream(decodedBytes);
PDDocument document = PDDocument.load(targetStream);
document.save("C:/test.pdf");
FileUtils.writeByteArrayToFile(new File("C:/test.pdf"), decodedBytes);
Using above code to convert to pdf.
Getting blob data of pdf from API :
Future<dynamic> getBlobdata(int pdfId) async {
try {
var response = await Dio().get(
"https://www.google.com/pdf/$pdfId",
options: Options(
responseType: ResponseType.bytes,
contentType: 'application/octet-stream',
),
);
var data = {"data": response.data.buffer};
return data;
} on DioError catch (error) {
var data = error.response.data;
return data;
}
}
Define file name and directory to save file :
String fileName = "pdf$pdfId";
final dir = await getExternalStorageDirectory();
var pdfBlob = await getBlobdata(1); // have to be in a asyn func to use await
Save Pdf :
final file = File("${dir.path}/$fileName.pdf");
await file.writeAsBytes(pdfBlob.asUint8List());
View Pdf in app :
await OpenFile.open("${dir.path}/$fileName.pdf");

angular2 file download in java

How could download a file using Angular2 and Java?
There is a GET HTTP call which returns the file data:
If receive a byte[] array, the file (in this case ODT, but could be
other format) opens as a document with the literal byte content
written in it: "UEsDBBQAAAgAAPBZjklexjIMJwAAACcAAAA"
If receive a blob object , it shows
"{"binaryStream":{},"wrappedBlob":{"binaryStream":{}}}" in the
document
Angular2 code:
goFile() {
//This service calls #angular/http for a GET request and returs the response
//ends up doing:
// this.http.get(url, {responseType: ResponseContentType.Blob})
// .map(res => res.blob())
this.myService.subscribe(result=> { this.saveFile(result); });
return false;
}
downloadFile(file: any) {
var blob = new Blob([file], {type: 'application/vnd.oasis.opendocument.text'});
var url= window.URL.createObjectURL(blob);
window.open(url);
}
Java code just reads the file and returns a blob or byte array (in each case tried):
byte[] file = FileUtils.getFile("E:/file.odt");
return file;
byte[] file = FileUtils.getFile("E:/file.odt");
Blob blob = Hibernate.createBlob(fichero);
return blob;
UPDATE
I believe the problem comes that data is being received as a json object, something setup in the system i am working.
Have tried intead to return byte[] from java and try to convert to a blob in Angular2 (for a txt file):
//file is returned by a call to http.get which has a map:
// .map(res => res.text())
var blob = new Blob([file], {type: 'text/plain'});
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
but returns a page with the byte content ("YWJj"), obviously the content received is not converted to a proper blob object.
Also tried with same result:
var byteArray = new Uint8Array(file);
var blob = new Blob([byteArray], {type: 'text/plain'});
there is not solution for different mime types without using additional plugins?

C# Download web page after java loading

How i can download webpage which uses java based loading mechanism?
Code below returns nearly empty document due site mechanism.
When viewed in browser you see "loading..." and after a while content is presented.
Also i want to avoid using WebBrowser control.
HtmlDocument doc = new HtmlDocument();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
if (!string.IsNullOrWhiteSpace(userAgent))
req.UserAgent = userAgent;
if (cookies != null)
{
req.CookieContainer = new CookieContainer();
foreach (Cookie c in cookies)
req.CookieContainer.Add(c);
}
var resp = req.GetResponse();
var resp_str = resp.GetResponseStream();
using (StreamReader sr = new StreamReader(resp_str, Encoding.GetEncoding("windows-1251")))
{
string r = sr.ReadToEnd();
doc.LoadHtml(r);
}
return doc;
Well you basically need a web browser to do the javascript running. Your webrequest now only fetches the data, as is, from the server.
You could use System.Windows.Forms.WebBrowser but its not pretty. This https://stackoverflow.com/a/11394830/2940949 might give you some idea on the basic issue.

Paste image from clipboard

I'm trying to paste image from clipboard in my website (like copy and paste). Appreciate if anyone could advice on this. Can I achieve this using HTML 5 or applet or any way. Any advice or any link for reference is highly appreciated.
Managed to do it with JavaScript.
JavaScript
if (!window.Clipboard) {
var pasteCatcher = document.createElement("apDiv1");
pasteCatcher.setAttribute("contenteditable", "");
pasteCatcher.style.opacity = 0;
document.body.appendChild(pasteCatcher);
pasteCatcher.focus();
document.addEventListener("click", function() { pasteCatcher.focus(); });
}
window.addEventListener("paste", onPasteHandler);
function onPasteHandler(e)
{
if(e.clipboardData) {
var items = e.clipboardData.items;
if(!items){
alert("Image Not found");
}
for (var i = 0; i < items.length; ++i) {
if (items[i].kind === 'file' && items[i].type === 'image/png') {
var blob = items[i].getAsFile(),
source = window.webkitURL.createObjectURL(blob);
pastedImage = new Image();
pastedImage.src = source;
pasteData();
}
}
}
}
function pasteData()
{
drawCanvas = document.getElementById('drawCanvas1');
ctx = drawCanvas.getContext( '2d' );
ctx.clearRect(0, 0, 640,480);
ctx.drawImage(pastedImage, 0, 0);
}
DIV
<div id="apDiv1" contenteditable='true'>Paste Test</div>
Even if applet is not signed, JNLP API is available.
ClipboardService cs = (ClipboardService)ServiceManager.lookup("javax.jnlp.ClipboardService");
Image c = (Image)cs.getContents().getTransferData(DataFlavor.imageFlavor);
at first, making a file(image) server.
then using js to listen to paste event.
code key word:
addEventListener 'paste' clipboard image
then using ajax upload to the file server. ajax resp the url.
finally making img tag by the url.
applet is out of date... ignore.

Categories