I need to download pdf file using Jersey Web Services
i already do the following but the file size received is always 0 (zero).
#Produces({"application/pdf"})
#GET
#Path("/pdfsample")
public Response getPDF() {
File f = new File("D:/Reports/Output/Testing.pdf");
return Response.ok(f, "application/pdf").build();
}
Please help to do the correct way, thanks !!
Mkyong always delivers. Looks like the only thing you are missing is the correct response header.
http://www.mkyong.com/webservices/jax-rs/download-excel-file-from-jax-rs/
#GET
#Path("/get")
#Produces("application/pdf")
public Response getFile() {
File file = new File(FILE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition","attachment; filename=test.pdf");
return response.build();
}
You can't just give a File as the entity, it doesn't work like that.
You need to read the file yourself and give the data (as a byte[]) as the entity.
Edit:
You might also want to look at streaming the output. This has two advantages; 1) it allows you to use serve files without the memory overhead of having to read the whole file and 2) it starts sending data to the client straight away without you having to read the whole file first. See https://stackoverflow.com/a/3503704/443515 for an example of streaming.
For future visitors,
This will find the blob located at the passed ID and return it as a PDF document in the browser(assuming it's a pdf stored in the database):
#Path("Download/{id}")
#GET
#Produces("application/pdf")
public Response getPDF(#PathParam("id") Long id) throws Exception {
Entity entity = em.find(ClientCase.class, id);
return Response
.ok()
.type("application/pdf")
.entity(entity.getDocument())
.build();
}
Related
I will have to do some development and I will need your logic please,
I'll try to be as clear as possible
I have a JSON file that will be sent to a Web Service to process it.
When the file arrives on this Web Service, I have to parse it.
First question :
Is it a #PostMapping to recover this file?
Since it's a file, I get it as a file like this:
#PostMapping( value="/getFile",
consumes = {"multipart/form-data"})
public void postFile(#RequestParam() MultipartFile file) throws IOException
I recover the file well, but the concern is that the #RequestParam parameter expects a file name, except that when the file is sent to the web service, I do not know its name yet,
Second Question :
So how do you parse this file into a string?
Thank you in advance for your precious help
For the first question:
Yep, #PostMapping is the right way to go. Regarding the file name bit, #RequestParam() does not expect the file name to be passed, it expects the "key" of the key-value pair where the value is the file being uploaded.
For example, when sending a file via a RestTemplate call, the file would be included in the POST call as somewhat like this:
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("uploadFile", getFileToUpload());
Here the key is "uploadFile", so your controller will look like this :
#PostMapping( value="/getFile",
consumes = {"multipart/form-data"})
public void postFile(#RequestParam("uploadFile") MultipartFile file) throws IOException
Checkout this tutorial : https://spring.io/guides/gs/uploading-files/
For the second question:
ByteArrayInputStream stream = new ByteArrayInputStream(file.getBytes());
String myFileString = IOUtils.toString(stream, StandardCharsets.UTF_8);
This should do. Cheers
I could able to use below code to upload a single photo, but I want to upload multiple photos with #FormDataParam
#POST
#Path("data/uploadPhoto")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadPhoto(#FormDataParam("data") InputStream photo) {
I tried to use #FormDataParam("file") List<InputStream> photos
but its not worked out, any suggestions?
Since each part of the request must have a unique name, you can not use the same name file for every image. The request must use different names.
It followes that your method must have one #FormDataParam for each file in the request. All of these must have different names.
public Response uploadPhoto(#FormDataParam("data1") InputStream photo1,
#FormDataParam("data2") InputStream photo2,
#FormDataParam("data3") InputStream photo3) {
You can upload multiple Files by Using FormDataBodyPart Class which allows you to get the form data and you can grab the multiple images as InputStream from it.
I've posted a sample below,
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public void uploadMultiple(#FormDataParam("file") FormDataBodyPart body){
for(BodyPart part : body.getParent().getBodyParts()){
InputStream is = part.getEntityAs(InputStream.class);
ContentDisposition meta = part.getContentDisposition();
doUpload(is, meta);
}
}
You Question possible duplicate of Selecting multiple files and uploading them using Jersey
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
While crawling a webpage I am getting various response types (image/text/html/json/css/js etc). I only need the .json files not the other ones. How can I filter other response types using HtmlUnit?
Problem is: The required data is stored in a specific .json file and that .json file doesn't have a unique url. So I am planning to filter other response type and download the content of all the json files. Later on I will clean the data.
Please help. Just an idea will be enough.
You can see modify the request and responses, as hinted here.
Check if the URL contains .json string, and then save it.
new WebConnectionWrapper(webClient) {
public WebResponse getResponse(WebRequest request) throws IOException {
WebResponse response = super.getResponse(request);
if (request.getUrl().toExternalForm().contains(".json")) {
String content = response.getContentAsString("UTF-8");
//save content
}
return response;
}
};
I want to send across resource(say a image) from some URL to front-end.
The typical way of doing this is to create a File and build the response. Is there any way in which I don't have to create the File in java code and still send the resource to front-end.
Front-end cannot access the URL due to some constraints.
Currently the Pseudo code looks like this.
File file = new File(fullPath);
FileUtils.copyURLToFile(url, file);
ResponseBuilder response = Response.ok(modulePDF);
I want to send content of URL to front-end without creating file. Is there any way?
What way did have in mind to actually obtain the file without creating a File object?
Not sure I fully understand the complete requirement, but you don't have to create a File object. You can send out a byte[], or simply write it to the response output stream by returning StreamingOutput.
#GET
public StreamingOutput getString() {
return new StreamingOutput(){
#Override
public void write(OutputStream out)
throws IOException, WebApplicationException {
// write to the `out` stream
}
};
}
For anything more than that, you will have to greatly elaborate on your requirement. The information you've provided, (especially the highlighted line) doesn't quite paint a clear enough problem as to what actual problem is you are facing.