getting image path in jsp - image

in my project I have to upload the image and show it in user profile view . Now I am successfully storing , I have problem in displaying image. the image is stored path D:/uploads so my image retrieving code in jsp is,
<c:set var="fileanme2" value="${teacherId.getPhoto()}"></c:set>
<%
String uploadFilePath2 = "D:" + "/" + "uploads";
%>
<c:set var="shlash2" value="/"></c:set>
<c:set var="pathValue2" value="<%=uploadFilePath2%>"></c:set>
<c:set var="string4" value="${pathValue2}${shlash2}${fileanme2}" />
<img alt="Image" src="${string4}" width="160" height="160"
class="img-thumbnail">
But image is not displaying , when I inspect the image element in browser in src attrib it showing path as D:/uploads/img when I hover mouse on it shows the path along with the project path how can I get the exact path for displaying image.

no need of any string concatenation and any extra work, you can do it in one line:
<c:set var="filePath" value="D:/uploads/${teacherId.getPhoto()}" />
and solutions for your problem:
1) if you are going to show image from you local file system then do like:
<img src="file:///D|/uploads/image_name.jpg"
width="200"
height="200"
alt="Image"/>
Warning: image may not be accessible when you publish your site.
2) create a servlet to handle GET request's of all images by passing name of image in url like:
#WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("getting photo...");
String imageName = request.getParameter("imageName");
System.out.println("imageName: "+imageName);
//set your upload path
File imageFile = new File("D:\\uploads\\"+imageName);
System.out.println("file exists: "+imageFile.exists());
// Get content type by filename.
String contentType = getServletContext().getMimeType(imageFile.getName());
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(imageFile.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + imageFile.getName() + "\"");
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(imageFile), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
// Gently close streams.
close(output);
close(input);
}
// Check if file is actually an image (avoid download of other files by hackers!).
// For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
if (contentType == null || !contentType.startsWith("image")) {
// Do your thing if the file appears not being a real image.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
}
// Helpers (can be refactored to public utility class)
private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
// Do your thing with the exception. Print it, log it or mail it.
e.printStackTrace();
}
}
}
}
and then in jsp use img tag like:
<img alt="Image"
src="<c:url value="/ImageServlet?imageName=${teacherId.getPhoto()}"/>" />
Source: BalusC image servlet

Related

XSL FO get image from server

Im using FOP version 2.1. I have a xsl fo template where i want to show images:
<xsl:variable name="ImagePath" select="defaultImageUrl"/>
<fo:external-graphic src="{$ImagePath}" content-width="scale-down-to-fit" width="100%"/>
Some images have a webadress like so:
https://upload.wikimedia.org/wikipedia/commons/thumb/b/b1/Tulipa_biflora_UME.jpg/800px-Tulipa_biflora_UME.jpg
But other images come from my webserver from address like:
https://localhost:4200/api/download/image/?fixedPrice=true&productId=1329&fileId=1304
This responds to endpoint:
public ResponseEntity<byte[]> getFileAsResponseEntity(#RequestParam boolean fixedPrice, #RequestParam long productId, #RequestParam long fileId) throws IOException, SQLException {
HttpHeaders headers = new HttpHeaders();
FileDownload fileDownload = productService.getProductFile(productId, fileId, fixedPrice);
headers.setCacheControl(CacheControl.noCache().getHeaderValue());
String n = fileDownload.getFileName().toLowerCase();
if (fileDownload.getFileTypeEnum().equals(FileTypeEnum.PICTURE) && (n.contains(".jpeg") || n.contains("jpg"))) {
headers.setContentType(MediaType.IMAGE_JPEG);
} else if (fileDownload.getFileTypeEnum().equals(FileTypeEnum.PICTURE) && (n.contains(".png"))) {
headers.setContentType(MediaType.IMAGE_PNG);
} else if (fileDownload.getFileTypeEnum().equals(FileTypeEnum.PICTURE) && (n.contains(".gif"))) {
headers.setContentType(MediaType.IMAGE_GIF);
}
return new ResponseEntity<>(fileDownload.getByteArray(), headers, HttpStatus.OK);
}
Is there a way for fo:external-graphic to accept these 2 different urls? Or is there something additional i need to do for it to work, since currently when the image comes from the webserver, the the resulting pdf file does not have the image in it, only a white space.
EDIT:
Here is the code that should make the XML to XSL to PDF:
byte[] xsl = IOUtils.toByteArray(this.getClass().getResourceAsStream("/browserDocument.xsl"));
byte[] xml = getBrowserDocument(filter, clientId, representId, ecatMain, showImage, language);
InputStream inStr = this.getClass().getResourceAsStream("/fop.xml");
FopFactory fopFactory = FopFactory.newInstance(new java.net.URI("."), inStr);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
javax.xml.transform.Source xsltSrc = new StreamSource(new ByteArrayInputStream(xsl));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(xsltSrc);
String xmlStr = new String(xml, "UTF-8");
xmlStr = xmlStr.replaceAll("<", "<");
xmlStr = xmlStr.replaceAll(">", ">");
javax.xml.transform.Source src = new StreamSource(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
return out.toByteArray();
I keep getting error message in the log files:
2019-01-30 16:07:48.300 ERROR 8424 --- [https-jsse-nio-8087-exec-3] org.apache.fop.apps.FOUserAgent : Image not found. URI: https://localhost:4200/api/efront/secure/download/product/image/?fixedPrice=false&productId=2823&fileId=1756. (No context info available)
It seems like it is calling the URL, but it is not getting the actual image from it. Maybe some issue with the image headers or the FOUseragent is getting blocked?
Well, implementing all above possible logic and seeing your code, I think URIResolver would help getting out of this as below:
Add it to your code : fopFactory.setURIResolver(new ResolveURIForWebServer());
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
public class ResolveURIForWebServer implements URIResolver {
#Override
public Source resolve(String href, String baseURI) throws TransformerException {
Source source = null;
try {
// CONVERT IMAGE TO INPUTSTREAM
source = new StreamSource(InputStream);
} catch (Exception e) {
} finally {
}
return source;
}
}
Hope it helps.

Why can I not show images on my server?

I have made this code for class but I just can't figure out why it is that when I click on a link, it won't show me the .jpg or .mp4 file. I've been scouring the Internet and I've tried converting the image from CMYK to RGB, adding even more CRLF to the end of the file and I simply can't understand why it gives me this error:
"The image cannot be displayed because it contains errors."
or
"The mp4 file cannot be displayed because it is corrupted"
This is my "welcome page"
<html>
<head>
<title> Welcome to my server</title>
</head>
<body bgcolor=white>
<p> Click one of the following: </p>
<p> Candy </p>
<p> Rossi vs Stoner </p>
</body>
</html>
And this is my server.
import java.io.*;
import java.net.Socket;
import java.util.*;
import java.awt.*;
import javax.imageio.*;
public class HTTPRequest implements Runnable
{
public static String CRLF = "\r\n"; // returning carriage return (CR) and a line feed (LF)
Socket socket;
// constructor
public HTTPRequest(Socket socket) throws Exception
{
this.socket = socket;
}
// Implement the run() method of the Runnable interface.
// Within run(), we explicitly catch and handle exceptions with a try/catch statement.
public void run()
{
try
{
processRequest();
} catch (Exception e)
{
System.out.println(e);
}
}
private void processRequest() throws Exception
{
//create an input and an output stream
InputStream instream = socket.getInputStream();
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
// create a buffer
BufferedReader buffRead = new BufferedReader(new InputStreamReader(instream));// reads the input data
// Get the request line of the HTTP request message.
String requestLine = buffRead.readLine();// get /path/file.html version of http
// Display the request line.
System.out.println();
System.out.println(requestLine);
// HERE WE NEED TO DEAL WITH THE REQUEST
// Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken();
String fileName = tokens.nextToken();
//this is so that i don't have to write /front.html at the start
if(fileName.equals("/")){
fileName="/front.html";
}
// attach a "." so that file request is within the current directory.
fileName = "." + fileName;
// Open the requested file.
FileInputStream fis = null;
boolean fileExists = true;
try
{
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e)
{
fileExists = false;
}
// Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists)
{
statusLine = "HTTP/1.0 200 OK" + CRLF; // 200 success code
contentTypeLine = "Content-type: " + contentType(fileName) + CRLF;
}// content info
else
{
contentTypeLine = "Content-type: text/html" + CRLF;// content info
entityBody = "<HTML>" + "<HEAD><TITLE>Not Found</TITLE></HEAD>"
+ "<BODY>Not Found</BODY></HTML>";
statusLine = "HTTP/1.0 404 Not Found" + CRLF;// 404 not found...
}
// Send the status line.
outStream.writeBytes(statusLine);
// Send the content type line.
outStream.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines.
outStream.writeBytes(CRLF);
// Send the entity body.
if (fileExists)
{
outStream.writeBytes(statusLine);// Send the status line.
outStream.writeBytes("\n"+contentTypeLine);// Send the content type line.
sendBytes(fis, outStream);
fis.close();
} else
{
outStream.writeBytes(statusLine);// Send the status line
outStream.writeBytes("\n"+contentTypeLine);// Send the content type line.
outStream.writeBytes(entityBody);// Send the an html error message info body.
}
System.out.println("*****");
System.out.println(fileName);// print out file request to console
System.out.println("*****");
// Get and display the header lines.
String headerLine = null;
while ((headerLine = buffRead.readLine()).length() != 0)
{
System.out.println(headerLine);
}
// Close streams and socket.
outStream.close();
buffRead.close();
socket.close();
}
// return the file types
private static String contentType(String fileName)
{
if (fileName.endsWith(".htm") || fileName.endsWith(".html"))
{
return "text/html";
}
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg"))
{
return "image/jpeg";
}
if (fileName.endsWith(".gif"))
{
return "image/gif";
}
if(fileName.endsWith(".mp4"))
{
return "movie";
}
return "application/octet-stream";
}
// set up i/o streams
private static void sendBytes(FileInputStream fis, DataOutputStream outStream)
throws Exception
{
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while ((bytes = fis.read(buffer)) != -1)// read() returns minus one, indicating that the end of the file
{
outStream.write(buffer, 0, bytes);
outStream.writeBytes("\r\n");
}
}
}
Please help me. thank you.
i don't get this line :
outStream.writeBytes("\r\n");
anyway, could you dump the post so that we could check what's going on ?

Display the PDF file stored on the webserver on Browser new window using Spring MVC

I have a requirement to show PDF files in a browser. I use Spring MVC. Is there a way I can do this without using AbstractPdfView? I do not want to render the PDF at runtime. All the PDF files will be stored in my webserver.
This is the code I am using. But this directly downloads the file instead of showing it up in a browser.
#RequestMapping(value = "/download" , method = RequestMethod.GET)
public void doDownload(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// get absolute path of the application
ServletContext context = request.getSession().getServletContext();
String appPath = context.getRealPath("");
String filename= request.getParameter("filename");
filePath = getDownloadFilePath(lessonName);
// construct the complete absolute path of the file
String fullPath = appPath + filePath;
File downloadFile = new File(fullPath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/pdf";
}
System.out.println("MIME type: " + mimeType);
String headerKey = "Content-Disposition";
response.addHeader("Content-Disposition", "attachment;filename=report.pdf");
response.setContentType("application/pdf");
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
Remove the line
response.addHeader("Content-Disposition", "attachment;filename=report.pdf");
This line precisely tells the browser to display a download/save dialog rather than displaying the PDF directly.
Oh, and make sure to close the input sytream in a finally block.

Display Image from bean

I have a bean with access to a image as byte[] here in the getImage method i convert a awt image to the byte array
public byte[] getImage() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] imageInByte = null;
try {
ImageIO.write( (BufferedImage)image, "jpg", baos );
baos.flush();
imageInByte = baos.toByteArray();
baos.close();
return imageInByte;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imageInByte;
}
I need to display the image with jsp within a table
like:
<table>
<c:forEach items="${beans}" var="bean">
<tr>
<td>${bean.name}</td>
<td>${bean.origin}</td>
<td>${bean.year}</td>
<td>${bean.number}</td>
<td>${bean.image}</td>
</tr>
</c:forEach>
Has it something to do with content type?
Create a img tag in your jsp file with src point to a servlet which will return the image byte array as a jpg image. You have to set correct mime type for the servlet output stream. One problem with this approach is that you have to save your image array in session for the servlet to pick it up.

Passing Image between servers for remote saving

My Spring application passes image file to Jersey application to get rid of all image manipulation tasks.
On receiving image, the Jersey application should save the image after several manipulations (crop, resize etc) and return image url.
For this, the Spring application has the below form in a JSP file:
<form method="POST" action="/asdf" enctype="multipart/form-data">
<input type="file" name="fstream"></input>
<input type="submit" value="Upload"/>
</form>
In my spring controller, I get DataInputString using:
DataInputStream in = new DataInputStream(request.getInputStream());
What would be an easy approach to carry out the desired action mentioned above?
How about converting it to BufferedImage in Spring app, POST it to the Jersey app, carry out required manipulations and save the image?
If that's fine, how do I convert DataInputStream to BufferedImage?
Thanks in advance.
Since there was no answer ...
I obtained byte array from submitted form data
Sent an object with byte[] being one of the attribute to REST server
On server side, I converted byte[] to BufferedImage which I scaled (using ImgScalr API) as required, and saved it.
#Path("/image")
public class ImageController {
#PUT
#Path("upload/{fileName}")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response upload(#PathParam("fileName") String fileName, FileBytes fileBytes){
byte[] bytearray = fileBytes.getFileBytes();
int len = bytearray.length;
if(len>0){
try {
int width=0, height=0, edge=0, px1=0, px2=0;
InputStream in = new ByteArrayInputStream(bytearray);
BufferedImage image = ImageIO.read(in);
File file = new File(Constants.PATH_TO_IMAGES+Constants.PATH_ORIGINAL+fileName+".jpg");
ImageIO.write(image, "png", file); //saving original image
width = image.getWidth();
height = image.getHeight();
//scaling as required
if(height>width){
px2 = (height-width)/2+1;
edge = width;
}else if(width>height){
px1 = (width-height)/2+1;
edge = height;
}else{
edge = width;
}
//using ImgScalr API to get scaled image
image = image.getSubimage(px1, px2, edge, edge);
image = Scalr.resize(image, 120);
file = new File(Constants.PATH_TO_IMAGES+Constants.PATH_THUMBNAIL+fileName+".jpg");
ImageIO.write(image, "png", file); //saving scaled image
} catch (Exception e) {
e.printStackTrace();
}
}
return Response.status(Status.OK).entity("Filename:"+fileName).build();
}
}

Resources