Opening a file on click of a link on a jsp page - java

I have a link(say open file) on a JSP page. On clicking that link, I need to open a file. The location of the file is present in a table on the Database. Since "onclick" event is a Javascript event, I am clueless on how to obtain the file location. Pls help. Im relatively new to this stuff. Pls give an idea to implement this. I can proceed based on the idea

On click call the servlet which reads the fie location from DB and redirect the user to that file location
or read the file and write it out to response and set the headers

That's an easy question.
Basically you must have a form that post's to a jsp page or servlet.
There you should read a hidden element that will point to the file.
There you should write the file on the response and send it back to the user.
See my post How to offer download of local PDF file in Java? for more info

Related

File upload with Ajax - not getting complete fileName

It is quite a common question but I can't find an answer to it
I have a simple HTML with an input text box (type=file) and a submit button. On clicking the submit button, I call a js function where I try to get the complete path of the file
var data = $('#fileName').val();
the issue is I am not getting complete file path of the file I am uploading. I know due to security reasons chrome gives me a C:\fakePath\filename and firefox gives me only the fileName. But in case I need a complete path what shall I do?
PS: Further I will make an ajax call and give that file path to the back-end which needs it to read that file using FileReader
You cannot get the complete path! there is no way to do that!! Even though you are on an intranet and you have enough permissions.
A workaround for this is to have a textarea and ask the user to enter the complete path of the file.
In short you can't have the full name of a file once is loaded on server side, you will just have the file name and its content in a raw byte array (among other attributes). This is not a Java thing nor other server side technologies issue, is related to browser implementation (but it looks that IE6 may contain a flaw about this).
Not directly related to your question but caught my attention
PS: Further I will make an ajax call and give that file path to the back-end which needs it to read that file using FileReader
Usually, you can't handle a file upload using ajax because it can lead to security holes. Still, there are some browsers (like Chrome and Firefox) that allows you to send a file using XMLHttpRequest but that isn't allowed on some browsers (like IE8-) so you have to use an iframe in order to make the file ajax uploading work.
In order to avoid handling all these problems, I would advice you to use a third-party js library that handles the ajax file upload. An example is blueimp jQuery file upload that also has Java server side examples (DISCLAIMER: I do not work in this project nor I'm associated with blueimp in any way). Note that using this plugin requires that you have a mid knowledge on HTML/JavaScript/jQuery/Java Server Side so if you're a starter it may take you some time to make it work, but once it does is pretty good.
I dont know which technology you are using.. but you can always get file name once it is uploaded on server (Using php or .net )
your steps to upload should be like below:
1) Upload file to the server (e.z. /uploadedFiles/...filename
2) Create a method which will fetch file name from the uploaded path
3) simply insert file name in to the database (this will give you flexibility to change folder name of uploaded docs in future if required)
Generally filenames are not stored as it is . to avoid name conflict in future. So it is a advisable to always rename your filename by adding minutes & seconds after itsname.
If any doubts do ask.
Hope it helps.
Browsers block the filepath access on javascript for securit reasons.
The behavior makes sense, because the server doesn't have to know where the user stores the file on his computer, it is irrelevant to the upload process.

Reading a CSV file from a JSP

I wrote a small log-in java program that works with servlets, and JSPs using the MVC pattern that allows me to register and log-in accounts(if we can call them that) to my local mySQL DataBase. I am using sessions to pass values between the servlet and the JSP, and I have a list of if statements on the servlet that work as validation for invalid inputs. Right now when my application is executed this happens:
Sign_Up.jsp opens up and displays UserName and Password fields with a submit button below it. Also it shows a link on the top left corner to the Log_In.jsp. If you enter an username and password that follows requirements, an account is created on the database, and you are redirected to the Welcome.JSP which only shows a few lines of text. (I am not checking weather the password and username entered are unique atm, so there are duplication entries in the user table on the DB)
If you click on the link at the top of the Sign_UP.jsp, then you are redirected to the Log_In.jsp. Here you are required to enter your credentials, if they exist on the database you are redirected to the Welcome.jsp , otherwise you are told that they are invalid and that you need to enter them again.
-----------------------------------THIS IS WHAT I WOULD LIKE TO DO NOW--------------------------------------
Once an account is validated and redirected to the Welcome.jsp I would like that page to show a button that says "Choose File", which when clicked will allow you to browse your computer for files. From there I should be able to select a .csv file that I can parse and enter into the database. Maybe the .csv will contain something as simple as:
Username , Password
UserTest1, 123
UserTest2, 234
UserTest3, 567
UserTest4, 890
So these are my questions regarding this whole procedure:
Is it possible to use JS inside a JSP to accomplish my task?
Is it a good idea to use JS inside a JSP to do it?
If I were to built a more complex website is it recommended to build it using html,css and jQuery code inside the JSP?
The whole idea is to build a a website that allows the admin ONLY to enter a .csv file containing a list of prices for items, that will be grabbed by the website and uploaded into the database, which in return will show a new stock of items for a certain product. I know that I am far from done, but this is just a start. :)
You don't need JavaScript to upload a file
I don't see how it would help. Just use a input of type file
You can of course use JavaScript, whatever you use at server-side to generate the HTML pages. Embedding JavaScript code inside HTML pages is a bad practice though. You should try to externalize the JS code to .js files as much as possible.
Just a few notes regarding the title and body of your question:
reading a CSV file is the job of the controller, not the job of the view
using the session to pass objects from a servlet controller to a view is not what you should do. You should use the request to do that.
You can't read files with JS because it doesn't have permission to access the filesystem.
You will have to upload the file into the server and get the parsing done from there.
There are tons of examples for JSP file uploading in the net.
Most complex websites employ the technologies/libraries you have listed so the answer is yes use them and it will increase usability and look and feel.

JSP: save a file on client without storing it on server

In my jsp someone wants to export a query result to csv. Can't use frameworks. At the moment, here is the process:
press button, go to servlet
prepare data for csv
make csv and save to server
back to jsp and let them download the fresh-made file from an anchor tag.
Thing is, I' don't want to create this file on server, as I have to dispose it afterwards, but I still want to give the user the "save as" window. So, is there a way, putting for example an OutputStream object in session, to achieve this result?
Thank you all!
A servlet can generate any type of content. So, when you click the button to run the servlet, simply have the servlet write the file back to the client at that time. You'll need to set the Content-type header to "text/csv" (and making sure that you set encoding properly). You don't need to set the Content-Length header; the browser can deal with that.
When the servlet returns data to the browser, the user will be prompted to save the file or open it with an application.
Yes. You don't need to save the file. Just hold it in the session and send it in-memory to the OutputStream. I would trash it after a given time or after delivery in order to save memory.
Set the content type and the content disposition appropriately. This will mean that the browser interprets the output correctly and prompts your user to save it or launch the appropriate application.
See this SO answer for more details.

Creating files under tomcat

I want to display a file from DataBase (stored as Blob).so for that i want to copy it under tomcat Server after that call the method that shows the file .
So is there a possibility to create a temporary folder in tomcat .
Any help will be appreciated
Many thanks
What you want is a Java Servlet which:
Retrieves the data blob from the database
Streams the data back to the browser as though a file were being returned
Here's an example from over on Java Ranch that I think summarizes the idea pretty well: http://www.coderanch.com/t/291337/JSP/java/Display-database-BLOB-jsp
Just remember that the servlet is tied to a URL, it receives a set of parameters via the query parameters on the end of the URL, and then it will use those to go get the data and return it. Make sure that the MIME type on the returned data is correct because that is the browser's clue what to do with the data streamed to it. That is, to the browser, the response is just a big bunch of data and the MIME type it sees with it helps it determine what action it should take. Should it be saved to a file, displayed, etc.
You can see some discussion of that portion of things in this Stack Overflow question: Help getting image from Servlet to JSP page
There already exists a temporary folder in tomcat.
tomcat/temp
Regards

Java download file from URL with unknown filename

I have URL that gets called from my java app that returns the save/open dialog for an Excel file.
At the moment, it opens in a new tab but I want to return the dialog box in the same window. I do not know the file name as it is dynamic and changes based on the parameters passed in.
I also do not want to save it somewhere as I want the user to have the choice of opening or saving.
Is there anyway of doing this in Java? I've only seen examples where the file name is known.
EDIT
The URL is hitting a CGI Script
Create a File object in your app from the url, store it in a temporary location then ask Excel to open it for you.

Categories

Resources