This is my jsp code.In the form tag the action attribute same .jsp page is needed. & how can i call FileUploadExample servlet from this jsp.
<form id="beneficiary_sales_details" name="beneficiary_sales_details"
action="beneficiary_sales_details.jsp" autocomplete="off" method="post">
<input type="file" id="datafile" name="datafile" size="40" />
<input type="button" id="cmdUpload" value="Upload" onclick = "unloadEvt();" />
This is the javascript i used to call servlet
function unloadEvt() {
document.location.href='/FileUploadExample';
}
This is the servlet to call.But I am unable to call this servlet from beneficiary_sales_details.jsp.Please suggest me any other option to call servlet from jsp
public class FileUploadExample extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("In fileupload servlet");
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField())
{
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists())
{
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
System.out.println(uploadedFile.getTotalSpace());
// bytesray = uploadedFile.length();
byte[] b = new byte[(int)uploadedFile.length()];
for (int i = 0; i < b.length; i++) {
// System.out.print(b[i]);
}
String str = b.toString();
System.out.println(" byte array in string---"+str);
out.println("<h1>"+str+"</h1>");
if(fileName!="")
item.write(uploadedFile);
else
out.println("file not found");
out.println("<h1>File Uploaded Successfully....:-)</h1>");
}
else
{
String abc = item.getString();
out.println("<br><br><h1>"+abc+"</h1><br><br>");
}
}
} catch (FileUploadException e) {
out.println(e);
} catch (Exception e) {
out.println(e);
}
}
else
{
out.println("Not Multipart");
}
}
}