What is the process of accessing a file from a JSP page?

I have a collection of PDF files saved in a local directory on D:/filesDir/. I am looking to showcase all the files from that folder on my JSP page. When a user clicks on a specific PDF file, it should directly open the corresponding file located in D:/filesDir/. Currently, this is how my code looks:

<% 
String sourceDirectory = "D:\\filesDir\\";
File f = new File(sourceDirectory);
String [] fileNames = f.list();
File [] fileObjects= f.listFiles();
%>
<UL>
<%
for (int i = 0; i < fileObjects.length; i++) {
if(!fileObjects[i].isDirectory()){
%>
<LI>
<A HREF="<%="D:/filesDir/"+fileNames[i] %>"><%= fileNames[i]%></A> 
&nbsp;&nbsp;&nbsp;&nbsp;
(<%= Long.toString(fileObjects[i].length()) %> bytes long)
<%
}
}
%>
</UL>

Although I can display all my PDF files from the filesDir folder on my JSP page with the above code, when a user clicks on a specific PDF file like abc.pdf, instead of opening D:/filesDir/abc.pdf, it redirects to localhost:8080/myapp/D:/filesDir/abc.pdf...

Is there a way to remove the application-specific path (localhost:8080/myapp/) and open the PDF file directly from the link?

Answer №1

If you're not working on a school assignment or practice exercise, I recommend exploring an already available solution. Personally, I have found the FileManager plugin for CKEditor to be incredibly useful for browsing files on the server as a standalone solution:

Check out the home page here:

You can also access the source code at this link: https://github.com/simogeo/Filemanager/tree/master/connectors/jsp

Adapting it to fit into existing apps is quite simple. Just download the plugin, make adjustments in the filemanager.config.js file, and you're good to go!

Answer №2

To resolve the issue, update the hyperlink line as follows:

<a href="<%="file://D:/webDirectory/"+fileNames[i] %>"><%= fileNames[i]%></a> 

However, if you want the files to be accessible on systems other than the server itself, it is recommended to move your file to the web directory and use a relative path for access.

Answer №3

Check out this code snippet for displaying file objects in a directory using Java.

<%@page import="java.io.File"%>
<html>
<body>
    <%
        String dirPath = "D:\\documents";
        File directory = new File(dirPath);     
        File[] files = directory.listFiles();
    %>
    <UL>
        <%
            for (int i = 0; i < files.length; i++)
            {
                if (!files[i].isDirectory())
                {%>
                    <LI><A HREF="file:\\\<%=files[i].getAbsolutePath()%>"><%=files[i].getName()%></A>
                        &nbsp;&nbsp;&nbsp;&nbsp; 
                        (<%=Long.toString(files[i].length())%> bytes long) 
                <%}
            }%>
    </UL>
</body>
</html>

Answer №4

<%@ page import="java.io.*"%>
<%
FileOutputStream output; 
try{
output = new FileOutputStream("C://Greetings.txt");
new PrintStream(output).println ("Not everything that shines is gold");
output.close(); 
}
catch (IOException exception){
output.println ("Could not write to file");
}
%>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After refreshing the page, users are redirected back to the login page

On my website, I created a main page and an index.html page that redirects to the main page through a login panel. The issue I am encountering is that when I log in successfully on the main page and then refresh the page, it takes me back to the login pag ...

What is the best way to know if a live stream is active on Twitch.tv?

This code snippet shows my implementation of the getStream method: public static Twitch_Stream getStream(String channelname) { try { String json = API.readJsonFromUrl("https://api.twitch.tv/kraken/streams?channel=" + channelname); ...

Building a properly formatted JSON object using JavaScript

I have been using the following code to build a JSON object with specific data: {"contacts":[{"provider":"Yahoo","firstName":"myname","lastName":"surname","nickname":"mynick","email":"example@example.com","photoURL":"http://l.yimg.com/dh/ap/social/profile ...

Having trouble receiving accurate intellisense suggestions for MongoDB operations

Implementing communication between a node application and MongoDB without using Mongoose led to the installation of typing for both Node and MongoDB. This resulted in the creation of a typings folder with a reference to index.d.ts in the server.ts file. In ...

Storing and securing passwords in Node/Express using hashing and salting techniques

Utilizing the Crypto module within Node's standard library is a necessity. I have established a POST route dedicated to handling a registration form: app.post('/superadmin/add-account', function(req, res) { // Creating shorthand variable ...

Utilizing Java's java.io.DataInputStream to read a binary file is yielding inaccurate data

I am struggling with reading a binary file that contains stock price data. Despite searching for solutions on multiple platforms and trying to use DataInputStream, I have not been successful. The existing tutorials and resources have not been helpful in so ...

Discovering the data-id value in an HTML element by clicking it with JavaScript and returning that value through a for loop

this is my unique html content <ul class="dialogs"> {% if t_dialogs %} <li class="grouping">Today</li> {% for item in t_dialogs %} <li class=&qu ...

"Utilizing Jquery's ajax feature to trigger a request to a Spring controller

Below is the configuration in my web.xml: <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> ...

Tips for changing XML attributes in Android/Java

I am dealing with an XML file that looks like this: <?xml version="1.0" encoding="utf-8"?> <Test1> <typ>task</typ> <datestamp>20150602153306</datestamp> <datecreate>20150602153306</datecreate> <task ...

Managing multiple sets of data in a structured form similar to an array

How Do I Send Form Data as an Array? Take a look at the code snippet below. I'm having trouble setting the index in product_attribute['index must be here']['key'] <tr v-for="index in attributes"> <td class="text-left ...

In Chrome, there is a flicker in the jQuery animated fade out before the callback function is triggered

I created a small feature that allows users to click on a text element, causing it to animate and fly to a specific location before disappearing. Check out this demo of the functionality. Below is the code snippet from the click handler (written in coffe ...

Creating a cinematic demise for a player through the lens of a camera

I've encountered a challenge with destroying the player through the camera in my application. The camera is set to follow the player (the ball), but it can only track the ball moving upwards. My goal is to have the player (ball) destroyed when it reac ...

Deselect a checkbox that is already selected and choose the current option in the multiselect dropdown

I've created a code that allows for single select in a multiselect dropdown, disabling other options once one is chosen. However, I don't want to disable the checkboxes and would like to uncheck the selected option if a new one is chosen, all whi ...

enforcing popstate in vue router

I have a situation where I have links in the middle of a webpage that change the content in a pane below using a nested router setup. My routes related to this issue are structured as follows: const router = { mode: 'history', routes: [ ...

Working with JSON data using jQuery

I am currently experimenting with Ajax calls and encountering difficulties in accessing the returned JSON data. Below is the code I have been working with: $('button').on('click', function() {  $.ajax({ url: 'http://quote ...

Tips for transferring data and executing a PHP script without page refresh

In my quest to access a product API from a web interface seamlessly, without causing any disruption to the user experience, I have encountered some challenges. The webpage and the main machine operate on separate servers, forcing me to resort to using PHP ...

Experiencing difficulties in retrieving property of a non-object when working with json and php

My current project involves using AngularJS to collect user input from a form, then sending this data to a PHP backend for processing. After decoding the JSON file in PHP, I then perform a database lookup to find information that matches the input values. ...

Using Conditional Rendering and ReactCSSTransitionGroup for Dynamic Animations

I have developed a small application that displays different components based on a Redux state. I am trying to add a "fade" animation when one of the components renders, but unfortunately, it is not working as expected. Here is my current setup: content.j ...

Implementing a jQuery click functionality on elements generated dynamically

I have a challenge where I need to attach a click event to buttons associated with each form in a dynamically created list of forms. Each form contains delete, edit, save, and cancel buttons. Initially, the save and cancel buttons are hidden. When the edit ...

The Vue.js integration fails to function within Laravel 5.5's environment

When the + sign is clicked, I want to add a new text field to an existing form. This functionality works fine in my code snippet, but not on my Laravel 5.5 site. No errors are showing up in my console. The HTML code goes into create.blade.php and the Vue ...