Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
2.2 kB
1
Indexable
Never
<%@ page import="java.io.BufferedReader" %>
<%@ page import="java.io.FileReader" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>File Browser and Reader</title>
</head>
<body>

<form action="" method="post" enctype="multipart/form-data">
    <label for="fileInput">Choose a file:</label>
    <input type="file" name="fileInput" id="fileInput">
    <input type="submit" value="Read File">
</form>

<%
    // Check if the form was submitted
    if ("POST".equalsIgnoreCase(request.getMethod())) {
        // Get the uploaded file
        Part filePart = request.getPart("fileInput");

        // Specify the directory to store the uploaded file on Linux
        String uploadDirectory = "/path/to/upload/directory/";

        // Extract the file name
        String fileName = getSubmittedFileName(filePart);

        // Create the full path to the uploaded file
        String filePath = uploadDirectory + fileName;

        // Save the file to the specified directory
        filePart.write(filePath);

        // Read and print the contents of the uploaded file
        try {
            FileReader fileReader = new FileReader(filePath);
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            // Read and print each line
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                out.println(line + "<br>");
            }

            // Close the BufferedReader
            bufferedReader.close();
        } catch (Exception e) {
            out.println("Error reading the file: " + e.getMessage());
        }
    }

    // Helper method to extract the file name from Part
    private String getSubmittedFileName(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
%>

</body>
</html>
Leave a Comment