Tuesday, December 26, 2006

# posted by G @ 5:40 PM
 

Uploading files to the server through JSP

Uploading files to the server through JSP
Step 1:
Code a simple HTML page that will take the user input :
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="jspl.jsp" enctype="MULTIPART/FORM-DATA" method=post>
Author: <input type="text" name="author" />
<br />
Company: <input type="text" name="company" />
<br />
Select file to upload <input type="file" name="filename" />
<br />
<input type="submit" value="Upload" />
</form>
</body>
</html>
Step 2:
Develop a JSP page that will handle the action and will call a java class file to upload the
File:
<%@ page language="java" import="uploadFile.SimpleBean" %>
<jsp:useBean id="TheBean" scope="page" class="uploadFile.SimpleBean" />
<%
TheBean.doUpload(request);
%>
Step 3:
The Java file for action (that is called through the JSP page) will look like this:
package uploadFile;
import java.io.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletInputStream;
import java.util.Calendar;
import java.util.Date;
public class SimpleBean
{
public void doUpload(HttpServletRequest request) throws IOException
{
Calendar calendar = Calendar.getInstance();;
Date date = calendar.getTime();
String fileName = date.toString();
fileName = fileName.replaceAll("GMT+05:30", "");
fileName = fileName.replace(':', '_');
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("C:\\"+ fileName + ".xml")));
ServletInputStream in = request.getInputStream();
int i = in.read();
while (i != -1)
{
pw.print((char) i);
i = in.read();
}
pw.close();
}
}
That’s it. Now just run the application after placing the files at the appropriate places as
required by your web server.
Isn’t it simple enough……