JSP How to Upload a File

Required Files:


1. page.jsp
2. pageupload.jsp



page.jsp

<html>
    <head>
        <title>File Upload in JSP</title>
    </head>
    <body>
        <FORM ENCTYPE="multipart/form-data" ACTION="pageupload.jsp" METHOD=POST>
        <br><br><br>
        <center><table border="2">
            <tr><center><td colspan="2">
                <p align="center"><B>PROGRAM FOR UPLOADING THE FILE</B></p></td></center>
            </tr>
            <tr>
                <td><b>Choose the file To Upload:</b></td>
                <td><INPUT NAME="F1" TYPE="file"></td>
            </tr>
            <tr><td colspan="2">
                <p align="right"><INPUT TYPE="submit" VALUE="send file"></P></td>
            </tr>
        </table>
        </center>
        </FORM>
    </body>
</html>


pageupload.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*" %>

<html>
<head>
<title>JSP File Upload</title>
</head>
<body>
<%
String s = request.getContentType();
if ((s != null) && (s.indexOf("multipart/form-data") >= 0))
{
DataInputStream in = new DataInputStream (request.getInputStream());
int length = request.getContentLength();
byte dataBytes[] = new byte[length];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < length)
{
byteRead = in.read(dataBytes, totalBytesRead, length);
totalBytesRead += byteRead;
}
String file = new String(dataBytes) ;
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") +
1,saveFile.indexOf("\""));
int lastIndex = s.lastIndexOf("=");
String boundary = s.substring(lastIndex + 1,s.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startpos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
File f = new File("F:\\"+saveFile);
FileOutputStream fileOut = new FileOutputStream(f);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
%><BrX<table border="2"><tr><td><b>You have successfully upload the file by
the name of:</b>
<% out.println(saveFile); %></td></tr></table>
<%
}
%>
</body>
</html>


Output:


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext