retrieve image from database using spring mvc - java

UserEntityManager.java
#RequestMapping(value = "getImages.do", method = RequestMethod.GET)
public byte[] getImage(final String username) {
Blob img = null;
byte[] imgData = null;
sql = "SELECT UserPhoto FROM u_logininfo WHERE LoginName = ?";
try {
img = jdbcTemplate.queryForObject(sql, new Object[]{username}, new RowMapper<Blob>() {
#Override
public Blob mapRow(ResultSet rs, int arg1)
throws SQLException {
Blob blob = rs.getBlob("UserPhoto");
return blob;
}
});
imgData = img.getBytes(1, (int) img.length());
return imgData;
//File file = new File
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
And this is my controller
UserController.java
#RequestMapping(value = "getImages.do" , method = RequestMethod.GET)
private ModelAndView viewImages(Model model){
String userName = (String)SecurityContextHolder.getContext().getAuthentication().getName();
byte[] image = userEntityManager.getImage(userName);
model.addAttribute("images", image);
return new ModelAndView("Fun Zone/Photo");
}
and jsp
<div class="col-sm-2" style="margin-top: 288px; margin-left: 291px;">
<img src="getImages.do">
</div>
I want to display the image on the .jsp page using Spring MVC 3 But image not display in jsp.

I'd suggest you to rewrite the controller. There seems so many things that are not exactly the way it's supposed to be. Do something like this:
#RequestMapping(value = "getImages.do", method = RequestMethod.GET)
public void viewImages(HttpServletRequest request, HttpServletResponse response) throws IOException {
// get the image
String userName = (String)SecurityContextHolder.getContext().getAuthentication().getName();
byte[] image = userEntityManager.getImage(userName);
// get MIME type of the file
String mimeType = "application/octet-stream";
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) image.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=image.jpeg");
response.setHeader(headerKey, headerValue);
// get output stream of the response
OutputStream outStream = response.getOutputStream();
// get input stream and a fixed size buffer
InputStream is = new ByteArrayInputStream(image);
byte[] buffer = new byte[4096];
// write data into output stream
int read = -1;
while(read = in.read(buffer)) != -1) {
outStream.write(buffer, 0, read);
}
// close output stream
outStream.flush();
outStream.close();
}
And also get rid of that RequestMapping on UserEntityManager.

Related

how return multivalued response

I'm currently writing a post API that gets a list of invoices number and then calls another API with resttamplate to obtain a pdf for every invoice number after that I concatenate all these pdf files to one file and return this file as a response, the problem here that there are invoices have an invalid invoice number so when I send this invoice number to the rest API can't get pdf so I want to get the failed invoices and send them back to the caller of my rest API, how to return pdf of the successful invoice and JSON object that contain a list of failed invoices number. Thanks in advance
that's my postApi
#PostMapping(value = "/gen-report")
public ResponseEntity<byte[]> generateReport(
#RequestHeader(value = HttpHeaders.AUTHORIZATION) String headerAuthorization) {
byte[] res = null;
List<String> failedInvoices = new ArrayList<>();
ResponseEntity<byte[]> response = null;
ArrayList<RequestParameters> requests = new ArrayList<>();
RequestParameters rp1 = new RequestParameters("360", "3600382368", "N");
RequestParameters rp2 = new RequestParameters("360", "3600382367", "N");
requests.add(rp1);
requests.add(rp2);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
List<byte[]> responses = new ArrayList<>();
for (RequestParameters parameter : requests) {
MultiValueMap<String, String> map = mobileOrderReportService.genrateReportService(parameter);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
response = null;
byte[] content = null;
content = requestReportByInvoiceNumber(entity);
if (content != null) {
responses.add(content);
} else {
failedInvoices.add(parameter.getOrderNum());
}
}
try {
res = mergePDF(responses);
} catch (DocumentException ex) {
Logger.getLogger(MobileOrderReportController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MobileOrderReportController.class.getName()).log(Level.SEVERE, null, ex);
}
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "pdf1.pdf";
headers.add("content-disposition", "inline;filename=" + filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
response = new ResponseEntity<byte[]>(res, headers, HttpStatus.OK);
return response;
}
this method returns the byte[] with the successful invoice or null with the failed invoice
public byte[] requestReportByInvoiceNumber(HttpEntity<MultiValueMap<String, String>> entity) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<byte[]> response = null;
try {
response = restTemplate.exchange(mobileOrderReportService.getUrl(), HttpMethod.POST, entity,
byte[].class);
byte[] content = response.getBody();
return content;
} catch (RestClientException ex) {
logger.error("request to UReport failed in requestReportByInvoiceNumber method !...");
return null;
}
}
method merge pdf and return one pdf
public byte[] mergePDF(List<byte[]> pdfFilesAsByteArray) throws DocumentException, IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Document document = null;
PdfCopy writer = null;
for (byte[] pdfByteArray : pdfFilesAsByteArray) {
try {
PdfReader reader = new PdfReader(pdfByteArray);
int numberOfPages = reader.getNumberOfPages();
if (document == null) {
document = new Document(reader.getPageSizeWithRotation(1));
writer = new PdfCopy(document, outStream); // new
document.open();
}
PdfImportedPage page;
for (int i = 0; i < numberOfPages;) {
++i;
page = writer.getImportedPage(reader, i);
writer.addPage(page);
}
} catch (Exception e) {
e.printStackTrace();
}
}
document.close();
outStream.close();
return outStream.toByteArray();
}
You already tagged "Multipart", which could be a solution. You're currently not sending one but just a byte array i.e. a file. With a multipart response, you could indeed have multiple (or in your case 2) parts:
Part with the merged PDF
List of failed invoice numbers either as plain text, JSON, or however you would like to send it.
A multipart response looks like this https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html (scroll down to the example)
An easier and "dirtier" way would be, to just include the faulty invoice numbers in your header response. You can define custom headers, so feel free to name it as you wish.
Either way, your client needs to be adapted, either by being able to read a multipart response (for which you need to write an HttpMessageConverter if your client isn't communicating reactively (Webflux)) or by reading the custom header.

Unable to download file in Spring MVC

My Controller to which the request is mapped-
I return the value from AJAX, to the controller-
$.ajax({
type: 'GET',
dataType: 'json',
contentType:"application/json",
url:"/Putty/downloadProcess/?param="+param
});
#RequestMapping(value = "/downloadProcess", method = RequestMethod.GET)
protected void download(#RequestParam("param") String value, HttpServletResponse response)
throws ServletException, IOException {
Properties prop = new Properties();
InputStream input = new FileInputStream("config.properties");;
prop.load(input);
System.out.println(value);
String path = prop.getProperty("path.MS1");
String filepath= path.concat(value);
System.out.println(filepath);
File downloadFile = new File(filepath);
FileInputStream inStream = new FileInputStream(downloadFile);
String mimeType = "application/octet-stream";
System.out.println("MIME type: " + mimeType);
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// forces download
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile);
response.setHeader(headerKey, headerValue);
System.out.println(response);
// obtains response's output stream
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inStream.close();
outStream.close();
This displays the filenames on my JSP
<c:forEach var="listValue" items="${files}">
<label onClick="download('${listValue}')">${listValue}</label>
<br>
</c:forEach>
The problem is that, I can see the MIME type on my console, along with the value returned by AJAX- The filename. But I do not get the Download dialog box, when I click on the file names, displayed on my JSP. Am I not handling the requests properly or I am missing something else.
Thanks!
Try it
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/octet-stream");
if (file.isFile())
{
response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadFile.getName() + "\"");
try (FileInputStream inputStream = new FileInputStream(downloadFile ))
{
IOUtils.copy(inputStream, out);
}
}
The Open/Save dialogue appears by default so we can not force anything. It is a browser specific settings that you cant change on the client side.
For Mozilla Firefox example :

Files not getting Downloaded in Spring

There is a page where i have files list. On cliking on any of the .txt it must get downloaded and a notification should be displayed as the notification we get in download anything on GoogleChrome.
This is my Js which is called after cliking on .txt files
Here i am doing is, i am getting the filename and the filepath of the selected file. And then using ajax sending those filename and filepath to the spring servlet.
if (options.downloadable) {
$(easyTree).find('.easy-tree-toolbar').append('<div class="fileDownload"><button class="btn btn-default btn-sm btn-primary"><span class="glyphicon glyphicon-circle-arrow-down"></span></button></div>');
$(easyTree).find('.easy-tree-toolbar .fileDownload > button').attr('title', options.i18n.downloadTip).click(function() {
var selected = getSelectedItems();
var fileName = $(selected).find(' > span > a').text();
alert("fileName**" + fileName);
var hrefValue = $(selected).find(' > span > a').attr('href');
alert("hrefValue**" + hrefValue);
if (selected.length <= 0) {
$(easyTree).prepend(warningAlert);
$(easyTree).find('.alert .alert-content').html(options.i18n.downloadNull);
} else {
$.ajax({
url: "/ComplianceApplication/downloadFileFromDirectory",
type: "GET",
data: {
hrefValue: hrefValue,
fileName: fileName
},
success: function(data) {
//$(selected).remove();
//window.location.reload();
},
error: function(e) {
}
});
}
});
}
This is my springController. Here I am getting all the data properly but the problem is file is not getting downloaded and am not even getting any error so that I can come to know what mistake I am doing.
#RequestMapping(value="/downloadFileFromDirectory",method = RequestMethod.GET)
public #ResponseBody void downloadFileFromDirectory(#PathVariable("fileName") String fileName,#RequestParam(value = "hrefValue") String hrefValue,HttpServletRequest request, HttpServletResponse response,Model model){
System.out.println("hrefValue***"+hrefValue);
String filePath = hrefValue;
ServletContext context = request.getSession().getServletContext();
File downloadFile = new File(filePath);
FileInputStream inputStream = null;
OutputStream outStream = null;
try {
inputStream = new FileInputStream(downloadFile);
response.setContentLength((int) downloadFile.length());
response.setContentType(context.getMimeType(downloadFile.getName()));
// response header
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
//String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
// Write response
outStream = response.getOutputStream();
IOUtils.copy(inputStream, outStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != inputStream)
inputStream.close();
if (null != outStream)
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Any suggestions ???
I usually use this kind of code with no problem:
public ResponseEntity<InputStreamResource> downloadFile(#PathVariable("idForm") String idForm)
{
try
{
File parent = new File(csvFilesPath);
File file = new File(parent, idForm+".csv");
HttpHeaders respHeaders = new HttpHeaders();
MediaType mediaType = new MediaType("text","csv");
respHeaders.setContentType(mediaType);
respHeaders.setContentLength(file.length());
respHeaders.setContentDispositionFormData("attachment", "file.csv");
InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
catch (Exception e)
{
String message = "Errore nel download del file "+idForm+".csv; "+e.getMessage();
logger.error(message, e);
return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
The problem it's in you ajax code, so you can use JQuery File Download.
It's as simple as
$.fileDownload('/url/to/download.pdf');
Here you can see a tutorial
http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/

How to compress image to be sent through HttpUrlConnection from applet to controller?

I addressed a problem with compress an image scanned by ScuGen Finger print sent through HttpUrlConnection from applet to controller, the code seems to be working but I need advise about it.
Here is the code in the applet when I click on Verify FingerPrint Image Button:
BufferedImage img1gray = new BufferedImage(deviceInfo.imageWidth, deviceInfo.imageHeight, BufferedImage.TYPE_BYTE_GRAY);
float imageQuality = 0.5f;
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
if (!writers.hasNext()){
throw new IllegalStateException("No writers found");
}else{
ImageWriter writer = (ImageWriter) writers.next();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(imageQuality);
writer.write(null, new IIOImage(img1gray, null, null), param);
byte[] data = baos.toByteArray();
HttpURLConnection connection = getHttpUrlConnection(data);
PrintWriter outputStream = new PrintWriter(connection.getOutputStream());
outputStream.write("image="+Base64.encodeBase64String(data)+"&index="+String.valueOf(jComboBoxFPIndex.getSelectedItem()));
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
this.jLabelStatus.setText(response.toString());
}else{
this.jLabelStatus.setText("Response Code = "+responseCode);
}
}
/*OutputStream outputStream = connection.getOutputStream();
outputStream.write(data);*/
} catch (Exception e) {
System.err.println(e.getMessage());
}
and Here is the controller where I received the image:
#RequestMapping(value = "/verifyfingerprint", method = RequestMethod.POST)
public #ResponseBody String verifyFingerPrint(HttpServletRequest request) throws BusinessException, IOException {
Loggers.logger.info("Verify Finger Print Image Start");
Loggers.logger.debug("Usertype = "+attribute.getType());
String message;
String fingerPrintImage = request.getParameter("image");
String fingerPrintIndex = request.getParameter("index");
if(fingerPrintImage == null || "".equals(fingerPrintImage)){
message = getResourceMessageHandler().getMessage("verify.finger.print.image.invalid", new String[]{}, Locale.ENGLISH);
Loggers.logger.error(message);
return message;
}
if(fingerPrintIndex == null || "".equals(fingerPrintIndex)){
message = getResourceMessageHandler().getMessage("verify.finger.print.index.invalid", new String[]{}, Locale.ENGLISH);
Loggers.logger.error(message);
return message;
}
FingerPrintValidationRequest fingerPrintValidationRequest = getRegistrationService().prepearFingerPrintValidationRequest(attribute, fingerPrintImage, fingerPrintIndex);
RestBuilder builder = RestBuilder.getInstance(null);
AjaxResult ajaxResult = builder.validateFingerPrintImage(fingerPrintValidationRequest,attribute,getRegistrationService(),getResourceMessageHandler());
Loggers.logger.debug(ajaxResult.toString());
message = ajaxResult.getMessage().get(0);
Loggers.logger.info("Verify Finger Print Image End");
return message;
}

How can I get download location browser in spring mvc controller?

The problem is next necessary to make file on server and after sending to client and print.
#RequestMapping(value = "/some", method = RequestMethod.GET)
public void getFileForPrint(HttpServletResponse response,
#RequestParam(value = "id", required = true) Long id,
#RequestParam(value = "print", defaultValue = "false") Boolean print) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fname);
ServletOutputStream out = response.getOutputStream();
somefile.write(out);
Desktop.getDesktop.print(new File("download location browser"));}
}
If you mean by when you are hitting an end point you want to download a file immediately then the following code should help you.
#RequestMapping(value = "/somePath", method = RequestMethod.GET)
#ResponseBody
public void getFileForPrint(HttpServletResponse response,
#RequestParam(value = "id", required = true) Long id,
#RequestParam(value = "print", defaultValue = "false") Boolean print) throws Exception {
String filename="nameOfFileWhenDownloaded.txt";
try {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
osw.write(contentsOfTheFile);
osw.flush();
osw.close();
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Error is sending file");
}
}

Categories

Resources