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

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();
});

Related

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?

How to download 10GB file with Angularjs, Java, Tomcat,Spring and REST?

When I download small file , everything is OK , but I need some way to download large files . If file large, Blob didn't created , haven't enough memory.
Download file without save on client , directly save to disk with many requests on the server or something like that.
My code on server is :
#RequestMapping(value = "/oneFile/{name}", method = RequestMethod.GET)
public void getOneFile( #PathVariable("name") String name, HttpServletResponse response,HttpServletRequest request) {
....
InputStream in = new FileInputStream(new File(file.getAbsolutePath()));
org.apache.commons.io.IOUtils.copy(in, response.getOutputStream());
response.flushBuffer();
On client and this is work for small size:
backupFileServer.downloadOneFileBrow(data)
.success(function(databack) {
var file = new Blob([ databack ], {
type : 'application/csv'
});
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = data;
document.body.appendChild(a);
a.click();
})
.error(function() {
alert($scope.DOWNLOAD_ERROR);
});
I tried something like this but didn't work :
var a = document.createElement('a');
a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(databack);
a.target = '_blank';
a.download = data;
document.body.appendChild(a);
a.click();
How someone idea how to do this or some example or code ....
Thank you in advance
You need to split your file into multiple files and rebuild the file with your server.
Because it's bad practice to upload a big file without splitting it, the user can be disconnect at 99% of the upload and he need to upload the whole file again.
An example here : https://flowjs.github.io/ng-flow/
A good example here : http://ryansouthgate.com/2015/12/24/upload-amazon-s3-using-angularjs/ with Amazon S3 and their SDK.

Unable to POST large html content to server on Chrome

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>

Trouble to save PDF file from a java web service using C#

I'm retrieving a PDF file from a web server java, returning a byte array.
Need save the PDF on the local machine using C #, but the file is saved completely in blank, I think it is because of the byte array format is different.
Here is my code:
StreamReader responseReader = new StreamReader(webStream);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/pdf";
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
byte[] docByte = Encoding.ASCII.GetBytes(response);
File.WriteAllBytes(#"C:\file.pdf", docByte);
Any suggestions on how to save the PDF file normally?
Thank you for listening
// ...
Stream webStream = webResponse.GetResponseStream();
using (var stream = File.Create(#"C:\file.pdf"))
{
webStream.CopyTo(stream);
}
Why don't you do it simply with WebClient like this?
using System.Net;
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(URL, #"C:\file.pdf");
}

Categories