I am building a server using Java's servlet and HTML forms.
I already managed to upload files: the user reach an HTML page, chose the file he/she wants to upload in his/her tree folder. The file is sent to a servlet I've written and downloaded on the server (actually I'm only running it on localhost for the moment, so the server is my 'My Documents' folder).
The next step I would like to make is this one:
The user (once logged, but I will manage to do that) reaches an HTML page, select a file that is hosted by the server and download it.
To make it, I will have to send to the 'Download Servlet' the name of the file. So here are my questions:
How to list the files that are in 'My Documents' on the HTML page.
How to send the name of the selected file to the servlet.
How to catch the 'request' and make a String of the name out of it.
To precise these two lasts points, please have a look at this:
List<FileItem> items = null;
items = upload.parseRequest(request);
FileItem item = items.get(0);
String fileName = item.getName();
The block above catches the name of the folder that is in the request. What I actually want to do is to do the same thing if what is in the request is a String (=catch the String contained in the request).
The File API will give you what you need for selecting the files in your directory.
List<File> files = Arrays.asList(new File("/your/directory").listFiles());
List<String> fileNames = new LinkedList<>();
for (File file : files) {
fileNames.add(somePrefix + file.getName());
}
request.setAttribute("fileNames", fileNames);
I do the above because you might not want to give the real path to your files, for security reasons. Once you have the list of file names in your request attributes, you can iterate over them in a jsp.
<form ...>
Select a file:<br />
<c:forEach items="${fileNames}" var="fileName">
<input type="radio" name="fileName" value="${fileName}">
</c:forEach>
<input type="submit" name="submit" value="submit">Submit
</form>
Now the files are each attached to an input element, which will translate to a request parameter. When the form is submitted, you can access the select file name by doing
String fileName = request.getParameter("fileName");
You can then append that file name to some directory structure and go and find it on the file system.
Related
I am currently able to serve up files from my server directory to the HTML front end. However, I am currently only able to have these files downloaded, or opened fully on the page. What I want to do is embed them within my webpage.
I can easily do this if the files are stored in the web directory but using the embed tag.
Currently I am doing something along the lines of this:
Servlet file :
#MultipartConfig
#WebServlet
public class FileServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File file = new File("filePath");
String mimeType = getServletContext().getMimeType(file.getName());
response.setHeader("Content-Type", mimeType);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "embed; filename=\"fileName.pdf\"");
Files.copy(file.toPath(), response.getOutputStream());
}
}
JSP :
<form action="getFile" method="post" id="fileForm">
<input type="hidden" name="fileName" value="<%out.print(cvKey);%>/<%out.print(name);%>.pdf"/>
</form>
Where the form is automatically submitted on page load.
I've been trying to set the source of the embedded tag to the output of the Servlet file, but nothing I have tried works in the way I want it to.
Any help would be amazing!!
UPDATE:
I've tried a few more things; including using an iframe like :
<iframe name="frame" width="500" height="300"></iframe>
And then setting the target of the form to the name of that frame. This still doesn't work and I just get an empty frame and the file gets downloaded :/.
EDIT :
Tried using the embed tag with a path directly to the file unsuccessfully :
My code :
<embed id="embeddedPDF" src="/home/user/resources/candidate.pdf" width="1000" height="1000" type='application/pdf'></embed>
And the error :
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
I am using JavaFileUpload and want to upload multiple pdf files.
HTML part:
#helper.form(action = routes.Application.uploadPost, 'enctype -> "multipart/form-data") {
<input type="file" id="inputFile" name="pdf" accept="application/pdf" multiple autofocus >
<p>
<input type="submit">
</p>
}
I must change body.getFile("pdf") asbody.getFiles() to be able to get every pdf document that I want to upload successfully.
I can see every document if I use getFiles() and if I use getFile("pdf") it just selects first document.
I tried to upload five pdf documents and here is the difference between getFiles() and getFile("pdf")
output of getFiles(): [play.mvc.Http$MultipartFormData$FilePart#3ac08835, play.mvc.Http$MultipartFormData$FilePart#362e6db5, play.mvc.Http$MultipartFormData$FilePart#2224a1dd, play.mvc.Http$MultipartFormData$FilePart#12fec5ae, play.mvc.Http$MultipartFormData$FilePart#14642c40]
output of getFile("pdf"): play.mvc.Http$MultipartFormData$FilePart#3ac08835
in the Java part, if I change getFile("pdf") as getFiles(), it tells me to add cast. So it offers me two options. One is to add FilePart cast, second is to change type of pdf to List<FilePart>
If I add FilePart cast for getFiles() like this FilePart pdf = (FilePart) body.getFiles(); PlayFramework shows me an exception: [ClassCastException: scala.collection.convert.Wrappers$SeqWrapper cannot be cast to play.mvc.Http$MultipartFormData$FilePart]
If I change type of pdf to List<FilePart>, it then offers me to add a cast to pdf.getFilename() like this: ((FilePart) pdf).getFilename(), also it offers me to add two casts to File file = pdf.getFiles() like this: File file = (File) ((MultipartFormData) pdf).getFiles(). If I run the code I also get the same exception.
Is there any way to upload multiple pdf documents in this case?
Half code: ( I can add full code if needed. The rest of code is parsing by using PDFBox and indexing into Solr and HBase
import play.mvc.Http.MultipartFormData;
import play.mvc.Http.MultipartFormData.FilePart;
MultipartFormData body = request().body().asMultipartFormData();
for(int i=0; i<body.getFiles().size(); i++) {
body = request().body().asMultipartFormData();
FilePart pdf = body.getFile("pdf"); //getFiles();
String fileName = pdf.getFilename();
File file = pdf.getFile(); //getFiles();
...
Play framework version: 2.4
First, the difference between getFiles() and getFile("pdf") is former gets list of files while latter get only one file.
Try the following code.
List<FilePart> fileParts = request().body().asMultipartFormData().getFiles();
for(FilePart filePart : fileParts) {
filePart.getFile();
}
Let's say i have created the file
String path = application.getRealPath("userSearchFolder");
String name = path + "/" + (String) session.getAttribute("username") + ".xml";
File file = new File(name);
And later I want to make it available as a link, for example
<a href"<%=file.toURI()%>">File</a>
What happens is I get the directory path not url path ->
file:/D:/Documents/NetBeansProjects/2012/GATE_Project/build/web/userSearchFolder/mjoraid.txt.xml
And when it reaches Firefox, I hover over the link and what i see is
file:///D:/Documents/NetBeansProjects/2012/GATE_Project/build/web/userSearchFolder/mjoraid.xml
When I right click and choose Copy link Location and paste it in URL the xml file opens, but when I click the link, nothing happens.
How could I get a link like this
http://localhost:8080/GATE_Project/somepage/somepage/mjoraid.xml
The getRealPath will give a File system path (hence "real"), as opposed to web app path. So you cannot make it a href.
The following should suffice.
<a href="/userSearchFolder/${userName}.xml">
(Of course you are risking data mining for such public accessible XML files.)
You could use a servlet to serve the file.
This tutorial shows how to serve a pdf file(!)
the theory is the same:
you load the file in the servlet
Set any required headers
write the data to the response
The ContentType should probably be "application/xml".
Ok, i did it manually, similar to how i used to do it in php, create a variable that contains the website main directory.
String searchFolderURL = "http://localhost:8080/GATE_Project/userSearchFolder/";
and then
<a href="<%=searchFolderURL + file.getName()%>" target="_blank" >See original txt File </a>
Thanks btw.
I am developing a web page in which I have to upload multiple files on
a single browse.
I am using html <input id="filelist" type="file" multiple=multiple>
This enables the multiple file selection and also retrieves the
full file path of all the selected file, which shows in file
upload text area.
<script language="JavaScript">
<!--
function showname(){
var filepath = document.form1.filelist.value ;
alert(filepath); //this shows only first filename among selected file
}
-->
</script>
But the problem is when I get the value of input, it returns only the first file
name among selected files.
Now how can I get the file paths which is shown in file upload text area.
Thanks!
This is browser specific. So you might be running this in a browser that doesn't support this. For example Firefox does. Here's an example of how to use this feature:
http://hacks.mozilla.org/2009/12/multiple-file-input-in-firefox-3-6/
I would consider using http://www.uploadify.com/about/ or http://www.fyneworks.com/jquery/multiple-file-upload/. They should help you out, and also add some cool features to your file upload form.
File paths are deliberately hidden from the page for security purposes. To look at the local filesystem you need to use Java, Active-x (meh), or Flash.
Is there a multipart POST library out there that achieve the same effect of doing a POST from a html form? for example - upload a file programmingly in Java versus upload the file using a html form. And on the server side, it just blindly expect the request from client side to be a multipart POST request and parse out the data as appropriate.
Has anyone tried this?
specifically, I am trying to see if I can simulate the following with Java
The user creates a blob by submitting an HTML form that includes one or more file input fields. Your app sets blobstoreService.createUploadUrl() as the destination (action) of this form, passing the function a URL path of a handler in your app. When the user submits the form, the user's browser uploads the specified files directly to the Blobstore. The Blobstore rewrites the user's request and stores the uploaded file data, replacing the uploaded file data with one or more corresponding blob keys, then passes the rewritten request to the handler at the URL path you provided to blobstoreService.createUploadUrl(). This handler can do additional processing based on the blob key. Finally, the handler must return a headers-only, redirect response (301, 302, or 303), typically a browser redirect to another page indicating the status of the blob upload.
Set blobstoreService.createUploadUrl as the form action, passing the application path to load when the POST of the form is completed.
<body>
<form action="<%= blobstoreService.createUploadUrl("/upload") %>" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<input type="submit" value="Submit">
</form>
</body>
Note that this is how the upload form would look if it were created as a JSP.
The form must include a file upload field, and the form's enctype must be set to multipart/form-data. When the user submits the form, the POST is handled by the Blobstore API, which creates the blob. The API also creates an info record for the blob and stores the record in the datastore, and passes the rewritten request to your app on the given path as a blob key.
You don't need a library; this is possible with the stock Java classes (example).
On the server side you will implement a Java Servlet solution that makes parsing HTTP request parameters very simple.
A complete and de facto standard HTTP implementation (included for example in the Android platform) you will find at Apache httpcomponent