Download excel/csv file from server on angular 8 application - java

I have a scenario where the REST API call to Java from Angular returns a response object which contains a HSSF Workbook object converted to string. I need to download the excel object that is in response on angular side. Following is my code in on client side which generates csv file, but the contents are not extracted. It just displays string 'HSSF Workbook' on downloaded file. How can I get the contents of file displayed. I see we have to use blob, which I am using, but still doesn't generate file properly.
Client Side code:
// making a service call to download file
this.servicecall(params).subscribe(result => {
if (response.hasOwnProperty('excelObject')) {
const downloaddata = response.exceldata;
this.downloadFile(downloaddata, 'fileName', 'text/csv;charset=utf-8');
}
});
// method to handle download of excel file
public downloadFile(buffer: any, fileName: string, ftype: string): void {
const data: Blob = new Blob([buffer], { type: ftype });
saveAs(data, fileName);
}

Related

org.apache.poi.poifs.filesystem.NotOLE2FileException

I am creating an UI where I ask the user to upload an existing excel file and I am getting this error. I have done some searching, and tried to use a POIFileSystem object before passing in the FileInputStream but that didn't. I am getting this error of the line that creates the workbook.
This my code:
public static Cell readExcelFile(byte[] byteFile){
if (file == null){
System.out.println("file is empty");
} else {
InputStream input = new ByteArrayInputStream(byteFile);
POIFileSytem fsPOI = new POIFileSytem(input);
HSSFWorkbook wb = new HSSFWorkbook(fsPOI);
//continues to read the file
}
}
I found an answer! So I as you see from the code above I passed my file as a byte array. Prior to that in my POST request I upload the file as a string and decode it from base 64 and into an byte array, that were the error occured. It wasn't decode correctly. I printed out what the String version of the file from the POST endpoint and that consist of "data:application/vmd.ms-excel;base64,OMBR4K(this the file data encoded in base 64 but Im not going to type all of it). Basically it wasn't decoding correctly because of everything before the comma was a regular text header. I spilt the string and saved everything after the comma in another string, and converted that into a byte array and decoded. Then my file was acceptable and I was able the create the workbook, and I also had to use .getSheetAt(int) instead of .getSheet("string")

Springboot API, receive file

I'm trying to make simple Springbot API that will be receive file from frontend. All tutorials that I found is complex and is too much for me. For educational purpose I just wanna to get file and print name of file.
Code that I tried:
#PostMapping(path="/postFile")
public void postFile(#RequestBody MultipartFile file){
System.out.println(file.getName());
}
Code return that variable file is null, and I don't know what I'm doing wrong.
Code from my frontend
function clickHandler(){
const formData = new FormData();
formData.append('File',selectedFile);
fetch("https://localhost:8443/postFile", {
method: 'POST',
body: formData
})
}
Use #RequestParam("File") instead of #RequestBody. As you are sending a form where your file is bounded to field 'File'.

how to upload excel file using Java Restful web services and AngularJS

I want to take Excel file from html input type="file" and pass that Excel file to my rest method java by http post method. I have a angular controller for that. I want to know how the controller should look like and what should be there in my rest method. I am using Apache POI to process the excel file.
You can have a angular method like this:
$scope.exelMethod = function (){
var excelObj = {};
excelObj.name = 'test';
excelObj.age = '20';
//you can write '/excel' as a rest web-service
$http.post('/excel,excelObj).success(function(response) {
console.log(response);// This will be a download path
//after this call the download function
});
}
In the middle layer you can write /excel service and map the excelObj from front end to a class view like this
public class ExcelView{
private String name;
private String age;
}
Now you can use this ExcelView class to map your data using POI. You will have to process the data and pass a download location of the file in the server to FE. In FE you will have to write a download function to download the file from the path you just got from the response.
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response getExcelData(ExcelView excelObj)
{ //this will be the service
}
if you need to know hot to write excel using poi check out this link
http://www.avajava.com/tutorials/lessons/how-do-i-write-to-an-excel-file-using-poi.html

What is the correct way to upload large Base64 encoded files with retrofit?

So I'm working with retrofit 2 which uses okhttp underneath. The below code snippet works but I get OOM errors for large files.
I believe this is because I am reading the file to a byte array.
What is the recommended way to work with this?
private void appendFileContentsToBody(Attachment attachment, MultipartBody.Builder requestBodyBuilder) throws IOException {
File file = new File(attachment.getAbsolutePath());
if(file.exists()){
RequestBody attachmentPart = RequestBody.create(null, Base64.getEncoder().encode(FileUtils.readFileToByteArray(file)));
requestBodyBuilder.addPart(Headers.of("X-Filename", attachment.getFilename()), attachmentPart);
}
}
You should not encode a file into Base64 before sending it, this should be done using stream, which will be done by Retrofit for you. So your code should look like
private void appendFileContentsToBody(Attachment attachment, MultipartBody.Builder requestBodyBuilder) throws IOException {
File file = new File(attachment.getAbsolutePath());
if(file.exists()){
RequestBody attachmentPart = RequestBody.create(MediaType.parse("application/pdf"), file);
requestBodyBuilder.addPart(Headers.of("X-Filename", attachment.getFilename()), attachmentPart);
}
}
where "application/pdf" - is MIME type of the particular file.
That way you will not suffer of OOM ever. However this approach might be implemented on a backend first cuz seems like now your backend implementation made applicable for web-apps only cuz it expects encoded file in a request body.

Send pdf as byte Array to front end and download a file JAVA (Play framework)

I'm creating pdf on my backend java application. when I save bytearray (my pdf file) on server storage pdf file is ok... I can open it looks good (98kb)
When I send this byte array as response for my request to a browser and save file as pdf on client computer only what I see after openning pdf is blank page. Weight of pdf(client) is bigger 128kB which is wierd.
I assume the problem is somewhere inside my javascript code:
$http
.post("/myUrl", JSON.stringify({img1: chart1URL,img2: chart2URL, img3: chart3URL,img4: chart4URL,img5: chart5URL,img6: chart6URL, site: $scope.criteria.siteNames[0], ward: $scope.criteria.wardNames[0]}),
{})
.success(
function(data){
debugger;
//var blob = new Blob([data], {type: 'application/*'});
//var objectUrl = URL.createObjectURL(blob);
//window.open(objectUrl);
var blob=new Blob([data], {type: 'application/octet-stream'});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="testFile.pdf";
link.click();
}
);
};
Why test file is bigger then file on backend?
I attach also backend code:
File file = ("myCorrectFile.pdf");
byte[] bytes = FileUtils.readFileToByteArray(file);
response().setContentType("application/octet-stream");
response().setHeader("Content-disposition","attachment; filename=test.pdf");
return ok(bytes);
Do you require the ajax call to be post? This can also be accomplished by get method as well.
The whole javascript code can be replaced by something like
window.open("url?param=" + parameters, "_self")
but get method has its own disadvantage of having maximum URL length of 2048 characters, depends how big your url would be.

Categories

Resources