make document available for download through java/servlet - java

I need to know if there is a way in java/servlet to make documents(doc,pdf) stored in database available for download to users in requested way(please see below),
for example there is a web page and the link for document in it
right now it is done this way:
if the user clicks that link than a new blank window opens and there the download dialog box is shown and the user is able to download the document but that blank window stays open
and the user have to close it manually
but wish to do it this way:
If the User clicks that link than directly staying on that page a download dialog box should show up asking them to save the file
a servlet url handles the download of the document which is responsible for extracting the doc form database and makes available for download to users
thank you for your time and effort

You need to add following headers in your servlet to make it a downloadable content so browsers don't try to display it,
String value = "attachment;filename=\"" + URLEncoder.encode(filename, "UTF-8") +'"';
response.setHeader("Content-Disposition", value);
response.setHeader("Content-Transfer-Encoding", "binary");
The filename is proposed filename and user can change it.

I wonder if your link html doesn't have something like:
<a href="/foo" **target="_blank"** ....>download</href>
Otherwise, it should work as you want.

This is a bug in IE which depends on several things, the content type is one of them. We had the same problem a few years ago but I don't remember the correct solution anymore, only that we struggled with this for quite some time. Try this:
Use the correct content type (application/pdf)
If that doesn't work, use a wrong file type (like application/octet-stream) which should tell IE to leave the file alone. You may have problems with the file extension, though.
Send or don't send the correct file size
Check which chunking mode you're using.
One of these things made IE behave. Good luck.

You need to remove target="_blank" from your <a> element.
Edit: as per your comments: you need to set Content-Disposition header to attachment. You can find here examples of a simple fileservlet and an advanced fileservlet to get some insights.

Related

Java HtmlUnit download pdf file

I want to download a pdf file from a website using HtmlUnit, but I haven't been able to do it. The download is triggered by clicking this:
<form name="form" action="ADIR_24046/civil/documentos/docuN.php" method="post" target="w1">
<input type="hidden" name="dtaDoc" value="7F547EA1167820365C20BA632B62A44E0B8F37564FCB3369284927C9763DE47F23DF398C061062F1">
<i class="fa fa-file-pdf-o fa-lg" aria-hidden="true" style="color:#ab5659; cursor:pointer;" onclick="$(this).closest("form").submit();"></i>
</form>
So far every time I try to do it, when I go to open the files, it says they are corrupt. My code for downloading the files is:
public void getFile(HtmlTableRow row, String folio) throws IOException {
HtmlPage pdfPage = (HtmlPage) frame.executeJavaScript("document.getElementById('historiaCiv').children[0].children[0].children[" +
row.getIndex() + "].children[1].children[0].children[1].children[0].closest('form').submit()").getNewPage();
ReadableByteChannel rbc = Channels.newChannel(pdfPage.getWebResponse().getContentAsStream());
FileOutputStream fos = new FileOutputStream(/* download path */, false);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
Is there any good way of doing this?
Without any more details and the real page to test i can only offer some hints for the problem solving.
Split you problem into two:
click the correct element and make sure HtmlUnit downloads the pdf
get the pdf from your program and save/analyze it
Before your start:
Make sure you have no javascript errors; maybe an error stops or breaks the processing. Use the simples (default) setup of the webclient. Change the config only to solve problems and make sure you know what you are doing. And make sure you use the latest (Snapshot) version available.
Step 1:
HtmlUnit works like a browser driven by you (your program) instead of a user clicking around. There should be normally no need to inject javascript like you did in your sample. Find the control the user usually clicks and simply call click on this. Because of ajax you might wait after the click some time to get all the async stuff done.
Use a web proxy like Charles (or enable HttpClient wire logging) to see the network traffic. Clicking the right control should lead to the pdf donwload visible in Charles.
Step 2
From you info i guess you are working with a page that does not do an ordinary pdf download on base of Html. Today there are many 'clever' javascript frameworks around doing strange things to make the download more user friendly. This implies that the download is done async and for you the result of the click operation is usually the htmlpage instead of the pdf result. If Step 1 was successful you have to get the newly opened window from the webclient and take the (pdf) content from this one.
Hope that helps, if you need more help you have to provide more details (or maybe you can try to use a more high level tool like wetator that does a lot of magic to deal with all this strange pages).

Return an Excel file from Java Servlet along with HTML content

Using java servlet i need to do a back-end DB query and populate the results in an excel file and provide to client user.
I have a working code of downloading Excel by setting the HtmlServletResponse object's contentType and Header like below:
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename="+ "Report" + ".xls");
But my question is in addition to providing this Excel sheet as a download i also need to send the 'initial search criteria' selected by the user as a HTML. And for html, i need to set the content type like below.
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
I think it's not possible to set the content type to 2 different values. How to solve this problem?
To phrase the problem in a different way -- "I have a HTML search form based on which user selects a search criteria - While providing the results in an excel save as file, i need to repopulate the same html so that search criteria selected by user is not lost".
I am new to Servlets and not sure if this is very straight forward. Thanks for the help.
You can not respond to the Service Request with more than one response. You'd need to show the search page with the search criterea and have the search page create the excel-file (in an iframe or something).
You can try to save your search criteria in cookies.
Here is some info about it http://www.journaldev.com/1907/java-servlet-session-management-tutorial-with-examples-of-cookies-httpsession-and-url-rewriting

How to show the content of a log file in new window when we click on a link in spring mvc

My main goal: When i click the link, a new browser window should be opened and displays the content of entire log file. And the window should not have an address bar and navigation buttons (Back, Forward).
Is there any approach to do this in Spring-MVC project?
Here is what i am doing now:
When i click the link, the controller will be called with a parameter logName.
Now the controller have access to get any kind of details of the log file like content, path, etc... I am setting all these details to an object and sending back to JSP.
Here i am not sure how to open a new window and display the content of the log file in that window.
Please suggest me an approach on this!!
It would be very helpful for me if you can share me with some examples...
Spring or JSP have nothing to do with it, the only way to force user's browser to open a link in a new tab is to use client-side Javascript. window.open() allows configuring the popup to hide certain interface elements (see all options in the documentation)
Your code would look something like:
<input type="button" value="Show Log" onclick="showLog(logName)">
function showLog(logName) {
var url = "/path-to-your-controller.html?logName=" + logName;
window.open(url, "LogPage", "toolbar=no,location=no,menubar=no");
}
However, I don't think using a customised browser popup is a good solution; it's been disappearing from the web for a reason. It would be more elegant to fetch raw data using AJAX and display it in a JS popup: it wouldn't interfere with user's page navigation (you tagged the question with jQuery, you could use jQuery UI for that).
What is more, I wouldn't be surprised if window.open wasn't supported by all browsers in the same way† - something to keep in mind if you're targeting a wider audience.
† seems that Chrome ignores location=no, for instance

Getting web content - browser does not support frames

I have a snippet of code like this:
webUrl = new URL(url);
reader = new BufferedReader(new InputStreamReader(webUrl.openStream()));
When I try to get html content of some page I get response that my browser doesn't support frames. So I do not get the real html of the page.
Is there a workaround?
Maybe to tell to the program to register as some browser?
For me it is critical only to get the html, then I want to parse it.
EDIT: Can not get src of the frame from the html in browser. It is hidden in js.
The "You don't support frames and we haven't put sensible alternative content here" message will be in the <noframes> element. You need to access the appropriate <frame> element, access its src attribute, resolve the URI in it, and then fetch data from there.
You must set a user-agent string in your HTTP request, so that the server thinks you are supporting frames. I suggest something like HtmlClient or HttpClient for this.

Can I specify a file type in GWT FileUpload?

I have a Gwt application and use a FileUpload to allow users to upload files.
Only certain types of files will be accepted and I have validation to check the file types once the user has selected it for uploading but I want to know if there is a way to only show files with certain extensions in the upload dialog box.
E.g. If the user has to upload a .doc file then I only want them to be able to see folders and .doc's, not All file types.
Using Zasz's answer and GWT Element it is possible to have an initial filter applied to the dialog box although it's not bulletproof...
myFileUpload.getElement().setAttribute("accept", ".txt");
At least this worked for me in a learning project. 'accept' has other formats too.
The nearest I can come up with is using this
<input type="file" accept="image/jpg,image/gif">
together with :
<form action="pat/to/action" enctype="multipart/form-data" method="post">
though it does no validations or makes any any changes to the open file dialog itself.
A better option will be to let the user select whatever file and when onClick() use a javascript function to check extension, and a neat little square area below the file upload control that gives the user feedback about the validity of the file he selected.
As per my knowledge
There is no programmatical way to only show files with certain extensions in the upload dialog box.
You need to put validations on selected file
You can create a comma separated string of mime types you want to support (below one is for xls, xlsx etc )
String mimeList = "application/vnd.ms-excel,application/msexcel,application/"
+ "x-msexcel,application/x-ms-excel,application/vnd.ms-excel,application/"
+ "x-excel,application/x-dos_ms_excel,application/xls,application/"
+ "vnd.openxmlformats-officedocument.spreadsheetml.sheet";
myFileUploader.setAcceptedTypes(mimeList);
Please note that there's no guarantee that this will work in all
browsers.
I have tested with Google chrome only and it works!
The W3C spec says only that this "provides the user agent
with a hint of file types to accept". How it does that is up to the
browser, and the browser is free to give the user the option to select
any file, notwithstanding your list of acceptable MIME types. So
you're still going to want to validate the file when the user clicks
the submit button or at the server side.

Categories

Resources