Some browsers have a security feature that prevents JavaScript from
knowing your file's local full path. It makes sense as a client, you
don't want the server to know your local machine's filesystem.Now when you browse a file from your local system you get the file name instead of File whole path. This results in many applications giving error as File Not Found.
Just create a Dynamic Web project from your IDE
You can use apache commons-fileupload-1.3.jar and commons-io-2.2.jar, Now create a Index.html
Index.html
Now create a Servlet named FileServlet
FileServlet
public class FileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
/**
* @see HttpServlet#HttpServlet()
*/
public FileServlet () {
super();
// TODO Auto-generated constructor stub
}
@Override
public void init() throws ServletException{
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
fileFactory.setRepository(filesDir);
this.uploader = new ServletFileUpload(fileFactory);
uploadFileAction = new UploadFileAction();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
String name = request.getParameter("username");
if(fileName == null || fileName.equals("")){
throw new ServletException("File Name can't be null or empty");
}
File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
if(!file.exists()){
throw new ServletException("File doesn't exists on server.");
}
System.out.println("File location on server::"+file.getAbsolutePath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("request.getContentType()\t"+request.getContentType());
if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
//String name = request.getParameter("name");
String name = request.getParameter("username");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
List fileItemsList = uploader.parseRequest(request);
Iterator fileItemsIterator = fileItemsList.iterator();
File file = null;
FileItem fileItem = null;
while(fileItemsIterator.hasNext()){
fileItem = fileItemsIterator.next();
if(fileItem.getName() != null){
System.out.println("FieldName="+fileItem.getFieldName());
System.out.println("FileName="+fileItem.getName());
System.out.println("ContentType="+fileItem.getContentType());
System.out.println("Size in bytes="+fileItem.getSize());
if(fileItem.getName().contains("/") || fileItem.getName().contains("\\")){
String fileName = FilenameUtils.getName(fileItem.getName());
System.out.println(fileName);
file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
}
else{
file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileItem.getName());
}
System.out.println("Absolute Path at server="+file.getAbsolutePath());
fileItem.write(file);
out.write("File "+fileItem.getName()+ " uploaded successfully.");
}
if(fileItem.getName() != null){
System.out.println("resp\t"+resp);
System.out.println("File "+fileItem.getName();
out.println("success");
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now create Listener named FileLocationContextListener
FileLocationContextListener
@WebListener
public class FileLocationContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
String rootPath = System.getProperty("catalina.home");
ServletContext ctx = servletContextEvent.getServletContext();
String relativePath = ctx.getInitParameter("tempfile.dir");
File file = new File(rootPath + File.separator + relativePath);
if(!file.exists()) file.mkdirs();
System.out.println("File Directory created to be used for storing files");
ctx.setAttribute("FILES_DIR_FILE", file);
ctx.setAttribute("FILES_DIR", rootPath + File.separator + relativePath);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
//do cleanup if needed
}
}
web.xml
When you run this program a tmpfiles directory is created in your tomcat server and then file that you browsed through your application gets copied to this location.
from your servlet when you do file.getAbsolutePath() you get the full path of your file.
Now you can easily upload it to your Database or read it as per your requirements
Just create a Dynamic Web project from your IDE
You can use apache commons-fileupload-1.3.jar and commons-io-2.2.jar, Now create a Index.html
Index.html
Now create a Servlet named FileServlet
FileServlet
public class FileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
/**
* @see HttpServlet#HttpServlet()
*/
public FileServlet () {
super();
// TODO Auto-generated constructor stub
}
@Override
public void init() throws ServletException{
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
fileFactory.setRepository(filesDir);
this.uploader = new ServletFileUpload(fileFactory);
uploadFileAction = new UploadFileAction();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
String name = request.getParameter("username");
if(fileName == null || fileName.equals("")){
throw new ServletException("File Name can't be null or empty");
}
File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
if(!file.exists()){
throw new ServletException("File doesn't exists on server.");
}
System.out.println("File location on server::"+file.getAbsolutePath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("request.getContentType()\t"+request.getContentType());
if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
//String name = request.getParameter("name");
String name = request.getParameter("username");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
List
Iterator
File file = null;
FileItem fileItem = null;
while(fileItemsIterator.hasNext()){
fileItem = fileItemsIterator.next();
if(fileItem.getName() != null){
System.out.println("FieldName="+fileItem.getFieldName());
System.out.println("FileName="+fileItem.getName());
System.out.println("ContentType="+fileItem.getContentType());
System.out.println("Size in bytes="+fileItem.getSize());
if(fileItem.getName().contains("/") || fileItem.getName().contains("\\")){
String fileName = FilenameUtils.getName(fileItem.getName());
System.out.println(fileName);
file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
}
else{
file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileItem.getName());
}
System.out.println("Absolute Path at server="+file.getAbsolutePath());
fileItem.write(file);
out.write("File "+fileItem.getName()+ " uploaded successfully.");
}
if(fileItem.getName() != null){
System.out.println("resp\t"+resp);
System.out.println("File "+fileItem.getName();
out.println("success");
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now create Listener named FileLocationContextListener
FileLocationContextListener
@WebListener
public class FileLocationContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
String rootPath = System.getProperty("catalina.home");
ServletContext ctx = servletContextEvent.getServletContext();
String relativePath = ctx.getInitParameter("tempfile.dir");
File file = new File(rootPath + File.separator + relativePath);
if(!file.exists()) file.mkdirs();
System.out.println("File Directory created to be used for storing files");
ctx.setAttribute("FILES_DIR_FILE", file);
ctx.setAttribute("FILES_DIR", rootPath + File.separator + relativePath);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
//do cleanup if needed
}
}
web.xml
When you run this program a tmpfiles directory is created in your tomcat server and then file that you browsed through your application gets copied to this location.
from your servlet when you do file.getAbsolutePath() you get the full path of your file.
Now you can easily upload it to your Database or read it as per your requirements