There is a servlet that accepts files from the client and stores them in a folder.
It is now necessary to list the files from this folder and create links to them (that is, click on the file name and it's downloaded from you).
Now just output a list of files in the form of text. How to create links to them? I read that for this it is enough to expose the headers, but how this is done and has not been found.
Sample Code:
public class FileListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileListServlet() {
super();
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String param = "/dirs";
PrintWriter w = res.getWriter();
res.setContentType("text/html");
String root="/dirs";
java.io.File dir = new java.io.File(root);
File[] fileList = dir.listFiles();
w.println("<H2><FONT COLOR=TEAL>" + "Total number of files in the choosen directory - " +
fileList.length + "</FONT></H2>");
w.println("<H3><FONT COLOR=PURPLE>" +
"Directory path - " + param + "</FONT></H3><HR>");
w.println("<TABLE BORDER=0 CELLSPACING=5>");
for(int i = 0; i < fileList.length; i++)
printName(fileList[i], w);
w.println("</TABLE><HR>");
}
private void printName(File name, PrintWriter output)
{
String type = name.isDirectory()
? " (Directory)" : " (File)";
output.println("<TR><TD>" + type + "</TD><TD><FONT COLOR=BLUE>"
+ name.getName() + "</FONT></TD></TR>");
}
public String getServletInfo()
{
return "This servlet shows a content of a directory" +
"mentioned in dirToShow parameter or property.";
}
}
I solved my problem. In case someone needs it or someone knows a more beautiful way.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
response.setContentType("text/html");
File currentFolder = new File(".");
File workingFolder = new File(currentFolder, "Sorted files");
String root = workingFolder.getAbsolutePath();
java.io.File dir = new java.io.File(root);
File[] fileList = dir.listFiles();
printWriter.println("<H2><FONT COLOR=TEAL>" + "Total number of files in the choosen directory - " +
fileList.length + "</FONT></H2>");
printWriter.println("<H3><FONT COLOR=PURPLE>" +
"Directory path - " + root + "</FONT></H3><HR>");
printWriter.println("<TABLE BORDER=0 CELLSPACING=5>");
for(int i = 0; i < fileList.length; i++) {
printName(fileList[i], printWriter);
}
printWriter.println("</TABLE><HR>");
}
private void printName(File file, PrintWriter output)
{
System.out.println(file.getName());
output.println("<tr><td><a href=\"https://Upload/DownloadServlet?name="
+file.getName()+"\">" + file.getName() + "</a></td></tr>" );
}
public String getServletInfo()
{
return "This servlet shows a content of a directory" +
"mentioned in dirToShow parameter or property.";
}
}
And DownloadServlet
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class DownloadServlet
*/
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DownloadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
String fileType = "multipart/form-data";
response.setContentType(fileType);
response.setHeader("Content-disposition", "attachment; filename=" + name);
File currentFolder = new File(".");
File workingFolder = new File(currentFolder, "Sorted files");
String root = workingFolder.getAbsolutePath();
File file = new File(root + File.separator + name);
OutputStream output = response.getOutputStream();
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[4096];
int lenght;
while( ( lenght = input.read(buffer) ) > 0 ) {
output.write(buffer, 0, lenght);
}
input.close();
output.flush();
output.close();
response.getOutputStream().flush();
response.getOutputStream().close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 2 years ago.
I'm trying to get a file uploaded by user in a servlet. I read it from here. But upload.parseRequest(request) gives compile time error saying RequestContext cannot to applied to HttpServletRequest object. why its not working here? I've also included commons-fileupload-1.3.2 and commons-io-2.5 in WEB-INF/lib folder.
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);}
catch(Exception e){
}
In servlet 3.0 You can do it with :
example class upload file :
package com.app.upload;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.Part;
/**
*
* #author ha: 12/05/2016 17:30
*/
public class UploadPicture {
private static final String EXTENSION = ".";
public static final String SAVE_DIR = "uploadImage";
private static UploadPicture uploadPicture = null;
private static final Logger LOGGER = Logger.getLogger(UploadPicture.class
.getName());
private UploadPicture() {
}
public String TranseferPicture(Part part, String appPath) {
String savePath = appPath + File.separator + SAVE_DIR;
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
String fileName = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String nameImage = fileName + EXTENSION + getExtensionImage(part);
try {
part.write(savePath + File.separator + nameImage);
LOGGER.log(Level.FINE, "Upload Picture to {0} ", savePath
+ File.separator + nameImage);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, ex.toString(), ex);
}
return nameImage;
}
private String getExtensionImage(Part part) {
return part.getContentType().split("/")[1];
}
public static UploadPicture createNewInstance() {
if (uploadPicture == null) {
uploadPicture = new UploadPicture();
}
return uploadPicture;
}
}
and in your servlet like this :
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.app.upload.UploadPicture;
/**
*
* #author ha date: 12/05/2016 17:42
*/
#WebServlet(urlPatterns = "/upload", loadOnStartup = 1)
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)
// 50MB
public class ControllerUploadPicture extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String appPath = request.getServletContext().getRealPath("");
Part part = request.getPart("file");
UploadPicture.createNewInstance().TranseferPicture(part, appPath);
getServletContext().getRequestDispatcher("/show.jsp").forward(request,
response);
}
}
in your jsp file
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload file</title>
</head>
<body>
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="file" /><br /> <input type="submit"
value="Upload" />
</form>
</body>
</html>
this example available in my account github
https://github.com/abdedaime/UploadPictureServlet
I am unable to upload file. There is no exception,no error but when the code is run, file doesn't uploaded. What could be the reason for it?
As debugged :
iterator.hasNext() returns false
`
<form action='UploadMatch' method='post' enctype="multipart/form-data">
<input type='file' />
<input type='submit' class='btn btn-default' id='uploadmatch' />upload
</form>
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
/**
*
* #author user
*/
public class UploadMatch extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter writer = response.getWriter();
String path = request.getParameter("Data");
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if( !isMultipart ) {
writer.println("File cannot be uploaded !");
} else {
DiskFileItemFactory diskFileItem = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(diskFileItem);
List list = null;
try {
list = fileUpload.parseRequest(request);
}catch(Exception exc) {
writer.println(exc);
}
Iterator iterator = list.iterator();
while(iterator.hasNext()) { // WHILE LOOP (DOESN'T ENTER)
FileItem fileItem = (FileItem)iterator.next();
if(fileItem.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
} else {
// Process form file field (input type="file").
String fieldName = fileItem.getFieldName();
String fileName = FilenameUtils.getName(fileItem.getName());
File file = new File(request.getServletContext().getContextPath(),fileName);
writer.println(">>>>>>>>>>W:/" + " " + fileName);
fileItem.write(file);
}
}
}
}catch(Exception exc) {
writer.println(exc);
}
}
}
Note : The code doesn't enter the while loop
I've a little doubt with this...how can i set/retrieve the value from a jsp page jscript string named "z" in a servlet.I need to use it in servlet...I'M exploring new thing n its a new thing for me as i"m new to these thing...Thanks for the quick help....i need the value of password if pass1 and pass2 are same,n then i need to retrieve it in servlet if pass1==pass2...tell me a way...for that i wrote a jscript to check pass1==pass2..
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>New User Registration</title>
<script>
function myFunction(){
var x = document.forms["newForm"]["pass1"].value;
var y = document.forms["newForm"]["pass2"].value;
if(x==y){
document.newForm.submit();var z=x;
return true;
}
else {
alert("Passwords not matching!!!");}
}
</script>
</head>
<body>
<h1>Form</h1>
<fieldset>
<form name=newForm action="RegServlet">Username:<input
type="text" name="username"><br>
Password:<input type="text" name="pass1" id="pass1"><br>
Confirm Password:<input type="text" name="pass2" id="pass2"><br>
<input type="submit" onclick=myFunction() value="Create"></input></form>
</fieldset>
</body>
</html>
servlet
package myPack;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RegServlet
*/
public class RegServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RegServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String s1=request.getParameter("username");
System.out.println(s1);
String s2=request.getParameter("");//HERE I NEED THE PAssword value if PASS!==PASS2
System.out.println(s2);
String c="jdbc:mysql://localhost:3306/test";
Connection con=null;
System.out.println("Connection OK");
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Done2");
con = DriverManager.getConnection(c, "root", "MyNewPass");
System.out.println("Done3");
PreparedStatement ps=null;
System.out.println("Done4");
String qs = "insert into userinfo values(?,?);";
ps = con.prepareStatement(qs);
ps.setString(1,s1);
ps.setString(2,s2);
System.out.println("Success");
ps.execute();
con.close();
}
catch (Exception e) {
System.out.println("Failed: " + e.toString());
// TODO: handle exception
System.out.println("Failed");}}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Create a hidden field in your form; then in your "onsubmit" event set the value of that field to z.
<input type="hidden" name="zValue" id="zValue">
in onsubmit event
document.getElementById("zValue").value="The value I want to send";
and retrieve in your servlet as any other parameter.
The following is an example i use in tomcat. It will get you all parameters that are send in a POST or GET request. Be advised that this does not cover multicast requests (which are needed for file transfers). I don't know if it will work for you, as you have not specified you servlet container.
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.util.*;
#WebServlet(description = "A simple request test.", urlPatterns = { "/requesttest" })
public class RequestTest extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Request Parameters";
out.println("<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");
Enumeration<String> paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.println("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.print("<I>No Value</I>");
else
out.print(paramValue);
} else {
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
EDIT
Seeing as you edited your question with your servlet code, the answer should be really simple.
String s2=request.getParameter("pass1");
This should get you the value that is transmitted within the password field. This is no different than you getting the username with String s1=request.getParameter("username");
I am getting null pointer exception here:
List fileItems = upload.parseRequest(req);
That happens if the number of line in the file is greater the 2000 approx, as I could upload the file of lines above 1000. Someone please help me out. The form is below.
<form name="fos_picks" id="fos_picks" action="<%=path%>/fos_upld" method="post" enctype="multipart/form-data" >
<br/><br/><br/><br/>
<p align="center">
<input type="file" name="file" size="50" /><br/>
<br/>
<input type="submit" class="buttons" value="Upload File" />
</p>
</form>
Upload controller code...
package file_proc;
import DBConn.DBConn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#WebServlet(name="file_upld", urlPatterns = {"/file_upld"})
public class file_upld extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 10 * 1024;
private File file ;
/* public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}*/
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, java.io.IOException {
// Check that we have a file upload request
java.io.PrintWriter out = res.getWriter( );
// out.println("entered");
isMultipart = ServletFileUpload.isMultipartContent(req);
res.setContentType("text/html");
if( !isMultipart ){
out.println("!multipart");
System.out.println("here");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:/temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
ServletContext servletContext = getServletContext();
String path = servletContext.getRealPath("/");
BufferedReader br=null;
String fileName="";
DBConn db = new DBConn();
try{
// Parse the request to get file items.
System.out.println("here1"+req);
List fileItems = upload.parseRequest(req);
// Process the uploaded file items
Iterator i = fileItems.iterator();
/* out.println("<html>");
out.println("<head>");
out.println("<title>Upload</title>");
out.println("</head>");
out.println("<body>");*/
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( "c:/Temp/" +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( "c:/Temp/"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
if(!file.exists())
{
File fold=new File(file.getParent());
fold.mkdirs();
}
fi.write( file ) ;
System.out.println("Uploaded Filename: " + fileName + "<br>");
}
}
}catch(Exception ce)
{
out.println("<font size='30' color='red'>Error Code 016</font>");
//out.println("Exception1: "+ce);
}
//read uploaded file and insert into table********************************************
// String newline = System.getProperty("line.separator");
// File file = new File(path+"//"+fileName);
// file.createNewFile();
try{
if(file.isFile())
{
br = new BufferedReader(new FileReader(file));
String str="";
String temp[]=null;
file.canWrite();
file.canRead();
file.setWritable(true);
db.conn.setAutoCommit(false);
while((str=br.readLine())!=null)
{
temp=str.split(" ");
// PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc VALUES(?,?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'))");
PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc(run_date,zone,location,bank,file_type,num_rec,ex_sett_date,ex_stat_date) "
+ "VALUES(STR_TO_DATE(?,'%m/%d/%Y'),?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'),STR_TO_DATE(?,'%m/%d/%Y'))");
ps.setString(1,temp[0]);
ps.setString(2,temp[1]);
ps.setString(3,temp[2]);
ps.setString(4,temp[3]);
ps.setString(5,temp[4]);
ps.setInt(6,Integer.parseInt(temp[5]));
ps.setString(7,temp[6]);
ps.setString(8,temp[7]);
ps.executeUpdate();
ps.close();
}
db.conn.commit();
db.conn.setAutoCommit(true);
db.conn.close();
br.close();
file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/status.jsp");
// rd.forward(req, res);
out.print("success");
// out.println("</html>");
}
else
{
out.println(file+" is not a file");
}
}catch(Exception ex) {
out.println("file name= "+fileName);
// out.println("DBEX= "+ex );
out.println("<font size='30' color='red'>Error Code 017 - Recommended date format = m/d/yyyy.</font>");
out.println("<font size='30' color='red'>Check the column order</font>"+ex);
//file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/error.jsp");
// rd.forward(req, res);
}finally{
try{
db.conn.close();
br.close();
}catch(Exception e){}
}
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, java.io.IOException {
doPost(request, response);
}
}
**** Here is form ******
<form name="file_proc" id="file_proc" method = "post" action="../file_upld" enctype="multipart/form-data">
<br/><br/><br/><br/>
<p align="center">
<input type="file" id="file" name="file" size="50" /><br/>
<br/>
<input type="submit" class="buttons" value="Upload File" />br/><br/><br/>
</p>
</form>
Upload controller code...
package file_proc;
import DBConn.DBConn;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#WebServlet(name="file_upld", urlPatterns = {"/file_upld"})
public class file_upld extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 10 * 1024;
private File file ;
/* public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}*/
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, java.io.IOException {
// Check that we have a file upload request
java.io.PrintWriter out = res.getWriter( );
// out.println("entered");
isMultipart = ServletFileUpload.isMultipartContent(req);
res.setContentType("text/html");
if( !isMultipart ){
out.println("!multipart");
System.out.println("here");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:/temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
ServletContext servletContext = getServletContext();
String path = servletContext.getRealPath("/");
BufferedReader br=null;
String fileName="";
DBConn db = new DBConn();
try{
// Parse the request to get file items.
System.out.println("here1"+req);
List fileItems = upload.parseRequest(req);
// Process the uploaded file items
Iterator i = fileItems.iterator();
/* out.println("<html>");
out.println("<head>");
out.println("<title>Upload</title>");
out.println("</head>");
out.println("<body>");*/
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( "c:/Temp/" +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( "c:/Temp/"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
if(!file.exists())
{
File fold=new File(file.getParent());
fold.mkdirs();
}
fi.write( file ) ;
System.out.println("Uploaded Filename: " + fileName + "<br>");
}
}
}catch(Exception ce)
{
out.println("<font size='30' color='red'>Error Code 016</font>");
//out.println("Exception1: "+ce);
}
//read uploaded file and insert into table********************************************
// String newline = System.getProperty("line.separator");
// File file = new File(path+"//"+fileName);
// file.createNewFile();
try{
if(file.isFile())
{
br = new BufferedReader(new FileReader(file));
String str="";
String temp[]=null;
file.canWrite();
file.canRead();
file.setWritable(true);
db.conn.setAutoCommit(false);
while((str=br.readLine())!=null)
{
temp=str.split(" ");
// PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc VALUES(?,?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'))");
PreparedStatement ps = db.conn.prepareStatement("INSERT INTO file_proc(run_date,zone,location,bank,file_type,num_rec,ex_sett_date,ex_stat_date) "
+ "VALUES(STR_TO_DATE(?,'%m/%d/%Y'),?,?,?,?,?,STR_TO_DATE(?,'%m/%d/%Y'),STR_TO_DATE(?,'%m/%d/%Y'))");
ps.setString(1,temp[0]);
ps.setString(2,temp[1]);
ps.setString(3,temp[2]);
ps.setString(4,temp[3]);
ps.setString(5,temp[4]);
ps.setInt(6,Integer.parseInt(temp[5]));
ps.setString(7,temp[6]);
ps.setString(8,temp[7]);
ps.executeUpdate();
ps.close();
}
db.conn.commit();
db.conn.setAutoCommit(true);
db.conn.close();
br.close();
file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/status.jsp");
// rd.forward(req, res);
out.print("success");
// out.println("</html>");
}
else
{
out.println(file+" is not a file");
}
}catch(Exception ex) {
out.println("file name= "+fileName);
// out.println("DBEX= "+ex );
out.println("<font size='30' color='red'>Error Code 017 - Recommended date format = m/d/yyyy.</font>");
out.println("<font size='30' color='red'>Check the column order</font>"+ex);
//file.delete();
// RequestDispatcher rd = req.getRequestDispatcher("./status/error.jsp");
// rd.forward(req, res);
}finally{
try{
db.conn.close();
br.close();
}catch(Exception e){}
}
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, java.io.IOException {
doPost(request, response);
}
}
**** Here is form ******
<form name="file_proc" id="file_proc" method = "post" action="../file_upld" enctype="multipart/form-data">
<br/><br/><br/><br/>
<p align="center">
<input type="file" id="file" name="file" size="50" /><br/>
<br/>
<input type="submit" class="buttons" value="Upload File" />br/><br/><br/>
</p>
</form>
here is the log4j stuff, it shows the error at filter.java, which i am not using in the current servlet.
[ERROR] 29:05(file_upld.java:doPost:172) failed!
java.lang.NullPointerException at
file_proc.file_upld.doPost(file_upld.java:120) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:641) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at filter.filter.doFilter(filter.java:16) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Here goes the filter.javapackage filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
public class filter implements Filter{
private FilterConfig config=null;
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
{
HttpServletResponse hsr = (HttpServletResponse) res;
hsr.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
hsr.setHeader("Pragma", "no-cache"); // HTTP 1.0.
hsr.setDateHeader("Expires", 0); // Proxies.
chain.doFilter(req, res);
}
#Override
public void destroy() { }
#Override
public void init(FilterConfig config) {
this.config = config;
}
}
Your concrete problem is caused by bad exception handling and tight-coupling view with the controller.
After filtering noise from your code, it goes roughly like:
File file = null;
try {
// ...
file = new File(...);
// ...
} catch (Exception e) {
out.println("...");
}
try {
if (file.isFile())
// ...
} else {
// ...
}
} catch (Exception e) {
out.println("...");
}
The NullPointerException is been thrown at the line with the if (file.isFile()) block. This thus means that the first try block threw an exception, hereby leaving the file as null.
The cause of the problem is two-fold:
The first try block is not returning from the servlet method on exception, but incorrectly continuing the code flow.
The second try block is not checking beforehand if the file is not null.
Your concrete problem is however much bigger. You're completely swallowing exceptions and printing irrelevant HTML code instead of throwing them through and/or logging the exceptions.
Replace your catch blocks as follows:
} catch (Exception e) {
throw new ServletException(e);
}
By default, this way the exception will be logged and be displayed in its full glory, complete with the stacktrace, in a HTTP 500 error page. The stacktrace gives you a wealth of information to understand the problem and fix it.
Unrelated to the concrete problem, there are many other conceptual and design mistakes in the code, but they are so far not directly related to the concrete problem. I would however recommend to take a pause and go through some sane Servlet books/tutorials/resources. This code seems to be just cobbled together based on snippets found in Google instead of being well thought out written. The first step would be understanding how servlets actually work: How do servlets work? Instantiation, sessions, shared variables and multithreading