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
Related
I am having HTML file which I want to send as a response for the rest call inside Apache camel RouteBuilder. The code looks like below
public class RestEndpointRouteBuilder extends RouteBuilder {
#Override
public void configure() {
rest("/form")
.post()
.produces(MediaType.TEXT_HTML_VALUE)
.to("file:target/classes/static/form.html");
}
But, I am getting below error when I call the API
org.apache.camel.component.file.GenericFileOperationFailedException: Cannot write null body to file: target\classes\static\form.html\ID-*****-***-****
at org.apache.camel.component.file.FileOperations.storeFile(FileOperations.java:245)
at org.apache.camel.component.file.GenericFileProducer.writeFile(GenericFileProducer.java:277)
at org.apache.camel.component.file.GenericFileProducer.processExchange(GenericFileProducer.java:165)
at org.apache.camel.component.file.GenericFileProducer.process(GenericFileProducer.java:79)
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145)
Basically, I want to return an HTML file, which is a ReactJS application, alongwith JS minified files. Could someone please help me with this?
There are several problems in your code:
The more appropriate HTTP method is rather GET instead of POST
The file component here is a to endpoint so it is used as a producer, in other words, it will save into the file instead of reading it as you expect.
The URI of the file component is incorrect, the URI format is file:directoryName[?options] which means that target/classes/static/form.html is supposed to be a directory, not a file.
What you try to achieve could be done as follow:
rest("/form")
// Fix #1: Use "get" instead of "post"
.get()
.produces(MediaType.TEXT_HTML)
.to("direct:fileContent");
from("direct:fileContent")
// Fix #2: Use "pollEnrich" to use the file component as a
// consumer to read the file
// Fix #3: Fix the URI to have the directory name on one side
// and the file name on the other side
.pollEnrich("file:target/classes/static?fileName=form.html");
NB: Even if what I described above will work, please note that a rest endpoint is not meant to be used for static content, you are supposed to use a reverse proxy instead.
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);
}
I have been learning spring and to get the things together I am making an e-commerce application. I have used rest api to connect client and server. Now i need to send images to the client. My images are already stored in src/resources folder. What i need to know is that how do i send those images through rest api. so that i can use it in my client
I am very noob at this. I tried google and all i can find is examples of image files uploading to the server. I can't find a example of sending file from server to client through rest api. i've been stuck in this for past three day
Here is my rest controller:
now i need to know what should i do next so that i can send images
#RestController
#RequestMapping("/api")
public class CategoriesRestController {
// autowire customer service
#Autowired
private CategoriesService service;
//add mapping for GET all customer
#GetMapping("/categories")
public List<Categories> getCategories() {
return service.getCategories();
}
// adding mapping for GET only one customer
#GetMapping("/categories/{categoryId}")
public Categories getCategory(#PathVariable int categoryId) {
Categories categories = service.getCategory(categoryId);
if(categories == null) {
throw new CustomerNotFoundException("Customer id not found- "+ categoryId);
}else {
return categories;
}
}
// adding mapping for POST/customer i.e. insert a customer
#PostMapping("/categories")
public Categories addCategories(#RequestBody Categories theCategories) { //#RequestBody will convert JSON to JAVA object
// just to make things clear... always set id to 0 when inserting new object
// so that it will be created instead of update
theCategories.setId(0);
service.saveCategories(theCategories);
return theCategories;
}
You might be thinking about the problem the wrong way. Instead of sending the image itself through the rest API, the HTML only needs the path to the image. You store the image in a directory, and you can pass the path to the image to your HTML. You could add a variable "imagePath" to Categories and the HTML could reference it in the tag
You can convert your images to base64:
byte[] fileContent = FileUtils.readFileToByteArray(new File(filePath));
String encodedString = Base64.getEncoder().encodeToString(fileContent);
and then send this property through your API. then in your client side you can use it like this:
<img src=json.encodedString />
Here json is an object which has been sent over API.
Before sending the encodedString you may appned at its beginning some things like below, to make it easier to display in front-end:
"data:image/png;base64,"
To display a base64 image in front-end you should use some thing like this:
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
Read more:
https://www.baeldung.com/java-base64-image-string
How to display Base64 images in HTML?
I'm using Spring Boot, Spring Data REST, Jasper Report (6.x).
I created a REST controller that should export a PDF report on disk and return a "ok" string to the client. So, it's a bit different from the usual use case in which the user what the PDF is sent back to the client.
According to best practice, I'm using the solution 4 of this reply: https://stackoverflow.com/a/27532493/2012635 for the "normal" use case in which the PDF is returned to the client:
#RequestMapping(value = "/refunds/{id}/export", method = RequestMethod.GET)
public ModelAndView exportPdf(#PathVariable("id") Long id, HttpServletRequest request, Locale locale) throws Exception {
Refund refund = refundRepository.findOne(id);
if (refund != null) {
ModelMap model = new ModelMap();
model.addAttribute("datasource", new JREmptyDataSource(1));
model.addAttribute("model", refund);
return new ModelAndView("RefundPdfView-IT", model);
} else {
throw new ResourceNotFoundException();
}
}
This approach is very clean, I've my mapping in the property file:
#REFUND
RefundPdfView-IT.(class)=org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView
RefundPdfView-IT.url=classpath:/reports/accounting/refunds/Refund-IT.jrxml
I'm wondering if I can reuse this approach to save the PDF on the disk in the server rather than send it back to the client.
I would like to reuse the mapping defined without hardcoding the position and names of reports.
Some advice would be appreciated.
First thing I would like to point out is you will need JasperExportManager.
exportReportToPdfFile(JasperPrint jasperPrint, java.lang.String destFileName)
to save a file locally in the server.
From your use case it is not clear why you want to save the file in server, I feel instead of saving the file you should save the search parameters. so that when you click on the parameters you will get/generate the pdf file again.
or alternatively you should use curl in the server and call the required url with parameters
I would like to upload a file from the web page using this strategy. i.e. Ajax file upload tutorial . It is going all fine, but the issue is on the server side, where I want to open this file and read its contents.
I am using the following signature for the method which is called on the submit of the form.
i.e.
public #ResponseBody String getFile(MultipartHttpServletRequest request)
Can any body please let me know that how can I extract the contents of the file?
MultipartHttpServletRequest extends MultipartRequest, which has methods for accessing the files.
You can do this:
MultipartFile file = request.getFile(paramName);
See http://docs.spring.io/spring-framework/docs/3.2.0.M1/api/org/springframework/web/multipart/MultipartRequest.html