I have a button (or link), and if I click on it, I want to open a HTML file. But I don't have the file, I have only the byte array of the HTML file. How could I open it in a new window, if I click on my opener button, to display the HTML file? Thank you!
You should make servlet which shows content of you html page. Example:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
// implement your page generations business logic in getHtmlPage
InputStream htmlPage = getHtmlPage();
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
I don't know how you exactly can determinate, which page you must show, so I encapsulate it into getHtmlPage method. Simplest way is make cache with pages and transfer into servlet page's key.
Related
I have a simple JSP page, which contains 2 buttons: View and Export. When View button is clicked I will fetch data from DB, keep a copy into session and write an HTML code into a label with the data. Later when user clicks Export I want to generate an excel file in the server(with the data from session) and download it to clientside.
Excel file is successfully created at serverside. I am using an AJAX request from clientside to download Excel file from server.
JSP code:
try{
String filepath=ExportToExcel(session.getAttribute("InvestmentDetails"));
//Setting file to download
response.setContentType( "application/x-download");
response.setHeader("Content-Disposition","attachment; filename=\"SIPInvestment_531.xls\"");
response.setStatus(200);
InputStream in = null;
ServletOutputStream outs = response.getOutputStream();
try {
File filetodownload=new File(filepath);
response.setContentLength(Integer.parseInt(String.valueOf(filetodownload.length())));
in = new BufferedInputStream(new FileInputStream(filetodownload));
int ch;
while ((ch = in.read()) != -1) {
outs.print((char) ch);
}
}
finally {
if (in != null) in.close();
}
outs.flush();
outs.close();
}
catch(Exception ex){
str=ex.getMessage();
}
Here is the Javascript:
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
}
}
xmlhttp.open("POST","/SIP/rptClientInvestmentDetails.jsp?requesttype=export",false);
xmlhttp.send();
The request reaches on JSP page. And without any exception it writes to response outputstream. But no download is pop up from browser. What can be the problem?
Ajax should be used for meta-languages, not for binary files.
A simple
<a href="/SIP/rptClientInvestmentDetails.jsp?requesttype=export"
target="_blank">Export</a>
is all you need.
If you make sure you said the response.setHeader("Content-Disposition","attachment you should drop the target-attribute as BalusC suggested.
I think you can use location.href="Provide the java class function name".This will transfer the control from jsp to java function without using the ajax call
With this code i am able to render a image from a servlet ,But my business says.I need to add a link say"www.google.com".If i click this image.Is there any way that i can access a image with the link on.I need to flush it directly from the servlet should not use jsp.Can any one please help me out.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ServletContext sc = getServletContext();
String filename = sc.getRealPath("image.JPG");
resp.setContentType("image/jpeg");
// Set content size
File file = new File(filename);
resp.setContentLength((int)file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
in.close();
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request , response);
// TODO Auto-generated method stub
}
}
You need to put an <a> element around the <img> element in the markup.
<a href="http://www.google.com">
<img src="imageServlet" />
</a>
By the way, the sc.getRealPath() suggests that your image file is already in public webcontent folder. Why not just using <img src="image.JPG"> instead? Or is the servlet heavily oversimplified?
In short you want to add a link say google.com and on click of it shows a image.
Firstly you don't need to send image as a response rather you need to anchor link and add javascript function onclick on that link.
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n" +
"<HTML>\n" +
"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
"<BODY>\n" +
"<a href='www.google.com'><img src='imagePath' /></a>\n" +
"</BODY></HTML>");
If I undestood correct you can return html with link on image:
<img src="yourImageRenderingServletPath">
So you will have one servlet that render html and second that render image. To prevent image buffering in browser you can add random param id = (new Random()).nextInt():
<img src="yourImageRenderingServletPath?id=124">
I have a servlet deployed under http://ip:8080/simple
The servlet is under package a.b.c
I have an html page in a.b.resources named Test.html.
The html has an img tag for an image.
In the servlet I do:
htmlFile = MyServlet.class.getResourceAsStream("/a/b/resources/Test.html");
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
byte[] bytes=new byte[htmlFile.available()];
htmlFile.read(bytes);
resp.setContentLength(bytes.length);
writer.print(new String(bytes));
writer.flush();
writer.close();
The html page appears on the browser but in the place of the image I see its alt description.
I have tried:
<img alt="Company A" src="./CompanyLogo.jpg">
<img alt="Company A" src="/a/b/resources/CompanyLogo.jpg">
<img alt="Company A" src="CompanyLogo.jpg">
But none of these works.
The jpg image is under /a/b/c/resources i.e. in the same directory as the HTML page.
I am using embedded Jetty.
What am I messing here?
The browser is trying to resolve those resources relative to the current request URI (as you see in browser address bar). Those resources of course does not exist in your public web content as you seem to have placed them in the classpath.
In order to solve this, you would really need to parse the HTML and change all domain-relative src and/or href attributes of <a>, <img>, <base>, <link>, <script>, <iframe>, etc elements to let them point to a servlet which streams those resources from the classpath to the HTTP response.
It's a bit of work, but Jsoup makes it easy. Here's an example which assumes that your servlet is mapped on an URL pattern of /proxy/*.
String proxyURL = request.getContextPath() + "/proxy/";
InputStream input = MyServlet.class.getResourceAsStream("/a/b/resources" + request.getPathInfo());
if (request.getRequestURI().endsWith(".html")) { // A HTML page is been requested.
Document document = Jsoup.parse(input, "UTF-8", null);
for (Element element : document.select("[href]")) {
element.attr("href", proxyURL + element.attr("href"));
}
for (Element element : document.select("[src]")) {
element.attr("src", proxyURL + element.attr("src"));
}
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(document.html());
}
else { // Other resources like images, etc which have been proxied to this servlet.
response.setContentType(getServletContext().getMimeType(request.getPathInfo()));
OutputStream output = response.getOutputStream();
byte[] buffer = new byte[8192];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
input.close();
Open it by http://yourdomain:yourport/contextname/proxy/test.html.
There is no way to do this without implementing a servlet that will read the image out of the resources file. Try this:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
byte[] bbuf = new byte[8192];
resp.setContentType(req.getSession().getServletContext().getMimeType( req.getPathInfo()));
InputStream in = MyImageServlet.class.getResourceAsStream("/"+req.getPathInfo());
OutputStream op = resp.getOutputStream();
int length;
while ((in != null) && ((length = in.read(bbuf)) != -1)){
op.write(bbuf,0,length);
op.flush();
}
in.close();
op.close();
}
then register it in your web.xml like so
<servlet-mapping>
<servlet-name>fetchimage</servlet-name>
<url-pattern>/fetchimage/*</url-pattern>
</servlet-mapping>
and then use it like so
<img alt="Company A" src="/fetchimage/a/b/resources/CompanyLogo.jpg">
You WILL need to implement a lot of error checking (A LOT OF ERROR CHECKING, just to clarify :)), filter the paths to make sure that someone can't just read your class files using the same technique, but some variation on this should work for you.
request.getRequestDispatcher("/a/b/Test.html").forward(request, response);
I want get all page content of website Examp : http://academic.research.microsoft.com/Author/1789765/hoang-kiem?query=hoang%20kiem
I used this code:
String getResults(URL source) throws IOException {
InputStream in = source.openStream();
StringBuffer sb = new StringBuffer();
byte[] buffer = new byte[256];
while(true) {
int bytesRead = in.read(buffer);
if(bytesRead == -1) break;
for (int i=0; i<bytesRead; i++)
sb.append((char)buffer[i]);
}
return sb.toString();
}
But the result missing some information such as information some hints about the author as shown below
can you give me some advice ! Thanks
The author details are loaded by ajax calls (click the "Net" tab in firebug and reload the page). If you want to get these details you will have to load the page in an environment that will execute javascript (ie: a browser).
I am pretty sure these contents are loaded into the page per JavaScript, and there's not really anything you can do about that when retrieving the page text from Java. You'll probably want to get a browser-plugin instead (Firefox has the largest repository of addons).
I know this has probably been asked 10000 times, however, I can't seem to find a straight answer to the question.
I have a LOB stored in my db that represents an image; I am getting that image from the DB and I would like to show it on a web page via the HTML IMG tag. This isn't my preferred solution, but it's a stop-gap implementation until I can find a better solution.
I'm trying to convert the byte[] to Base64 using the Apache Commons Codec in the following way:
String base64String = Base64.encodeBase64String({my byte[]});
Then, I am trying to show my image on my page like this:
<img src="data:image/jpg;base64,{base64String from above}"/>
It's displaying the browser's default "I cannot find this image", image.
Does anyone have any ideas?
Thanks.
I used this and it worked fine (contrary to the accepted answer, which uses a format not recommended for this scenario):
StringBuilder sb = new StringBuilder();
sb.append("data:image/png;base64,");
sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(imageByteArray, false)));
contourChart = sb.toString();
According to the official documentation Base64.encodeBase64URLSafeString(byte[] binaryData) should be what you're looking for.
Also mime type for JPG is image/jpeg.
That's the correct syntax. It might be that your web browser does not support the data URI scheme. See Which browsers support data URIs and since which version?
Also, the JPEG MIME type is image/jpeg.
You may also want to consider streaming the images out to the browser rather than encoding them on the page itself.
Here's an example of streaming an image contained in a file out to the browser via a servlet, which could easily be adopted to stream the contents of your BLOB, rather than a file:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
ServletOutputStream sos = resp.getOutputStream();
try {
final String someImageName = req.getParameter(someKey);
// encode the image path and write the resulting path to the response
File imgFile = new File(someImageName);
writeResponse(resp, sos, imgFile);
}
catch (URISyntaxException e) {
throw new ServletException(e);
}
finally {
sos.close();
}
}
private void writeResponse(HttpServletResponse resp, OutputStream out, File file)
throws URISyntaxException, FileNotFoundException, IOException
{
// Get the MIME type of the file
String mimeType = getServletContext().getMimeType(file.getAbsolutePath());
if (mimeType == null) {
log.warn("Could not get MIME type of file: " + file.getAbsolutePath());
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
resp.setContentType(mimeType);
resp.setContentLength((int)file.length());
writeToFile(out, file);
}
private void writeToFile(OutputStream out, File file)
throws FileNotFoundException, IOException
{
final int BUF_SIZE = 8192;
// write the contents of the file to the output stream
FileInputStream in = new FileInputStream(file);
try {
byte[] buf = new byte[BUF_SIZE];
for (int count = 0; (count = in.read(buf)) >= 0;) {
out.write(buf, 0, count);
}
}
finally {
in.close();
}
}
If you don't want to stream from a servlet, then save the file to a directory in the webroot and then create the src pointing to that location. That way the web server does the work of serving the file. If you are feeling particularly clever, you can check for an existing file by timestamp/inode/crc32 and only write it out if it has changed in the DB which can give you a performance boost. This file method also will automatically support ETag and if-modified-since headers so that the browser can cache the file properly.