java.lang.NullPointerException when processing file upload - java

I would be very gratefull if you could find where is my problem and how can I fix it. (java.lang.NullPointerException)
here is my html from where I get a textfield and I upload 2 files
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>File Upload:</h3>
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<br><br><br><br><br>
Insert your ID (marca) - ex: 101358
<br>
<input type="text" name="rid" size="40" />
<br><br>
Browse your files:
<br>
<input type="file" name="file" size="30" />
<br />
<br/>
<input type="file" name="file" size="30" />
<br />
<br>
<input type="submit" value="Upload File" />
</form>
</body>
</html>
in this servlet I save the uploaded files into a specific folder and after that I am connecting to a database where I want to store the string got from html and the file paths from the uploaded files
UploadServlet.java
public class UploadServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
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 );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet 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();
String 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:/UploadedFiles/" + fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( "C:/UploadedFiles/" + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + " --- saved in C:/UploadedFiles/ " + "<br>");
}
FileItem fi2 = (FileItem)i.next();
if ( !fi2.isFormField () )
{
// Get the uploaded file parameters
//String fieldName2 = fi2.getFieldName();
String fileName2 = fi2.getName();
//String contentType2 = fi2.getContentType();
//boolean isInMemory = fi2.isInMemory();
//long sizeInBytes = fi2.getSize();
// Write the file
if( fileName2.lastIndexOf("\\") >= 0 ){
file = new File( "C:/UploadedFiles/" + fileName2.substring( fileName2.lastIndexOf("\\"))) ;
}else{
file = new File( "C:/UploadedFiles/" + fileName2.substring(fileName2.lastIndexOf("\\")+1)) ;
}
fi2.write( file ) ;
out.println("Uploaded Filename: " + fileName2 + " --- saved in C:/UploadedFiles/ " + "<br>");
}
//}
out.println("</body>");
out.println("</html>");
String idmarca = request.getParameter("rid");
String itemName1 = fi.getName();
String path1 = new String("C:\\UploadedFiles\\" + itemName1.substring(itemName1.lastIndexOf("\\")));
String itemName2 = fi2.getName();
String path2 = new String("C:\\UploadedFiles\\" + itemName2.substring(itemName2.lastIndexOf("\\")));
Connection con = null;
PreparedStatement ps;
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:upload";
con = DriverManager.getConnection(db, "", "");
String sql = "INSERT INTO file1(marca,file1,file2) VALUES(?, ?, ?)";
ps = con.prepareStatement(sql);
ps.setString(1, idmarca);
ps.setString(2, path1);
ps.setString(3, path2);
int s = ps.executeUpdate();
if(s>0){
System.out.println("Uploaded successfully !");
}
else{
System.out.println("Error!");
}
}
catch(Exception e){
e.printStackTrace();
}
finally {
// close all the connections.
//ps.close();
//con.close();
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " + getClass( ).getName( )+": POST method required.");
}
}
java.lang.NullPointerException
at UploadServlet.doPost(UploadServlet.java:126)
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 org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
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:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)

OK, my problem is in line String idmarca = request.getParameter("rid"); it gets the text from the html textfield. Before adding this textfield I was able to save the file paths of the uploaded files.
When using multipart/form-data requests, the form data pars are not available as request parameters by request.getParameter(). They are only available as form data parts by request.getPart(). But as you're using Apache Commons FileUpload (perhaps you aren't using the new Servlet 3.0 version yet wherein the getPart() method is available), then you should actually be using the very same API to retrieve the text field value.
Continue iterating the fileItems. The text field value is in there.
See also:
How to upload files to server using JSP/Servlet?

Related

File upload to server using java

I'm trying to upload a file to a server.I'm using apache tomcat and java .
Following is my code,
Fileuploadservlet.java:
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
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("/UploadServlet")
public class FileUploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 1000 * 1024;
private int maxMemSize = 40 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ) {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
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 );
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet 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();
String 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( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
} else {
file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
} catch(Exception ex) {
System.out.println(ex);
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>FileUploadServletExample</display-name>
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
C:\Users\e48265\apache-tomcat-7.0.81\webapps\data\
</param-value>
</context-param>
<welcome-file-list>
<welcome-file>upload.jsp</welcome-file>
</welcome-file-list>
</web-app>
upload.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload Demo</title>
</head>
<body>
<center>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "UploadServlet" method = "post" enctype = "multipart/form-
data">
<input type = "file" name = "file" size = "50" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</center>
</body>
</html>
I'm getting the following output after running upload.jsp file and clicking upload button,
java.io.FileNotFoundException: null\quizlet.txt (The system cannot find the path specified).
Can anyone help me with ?
Note:quizlet.txt is my file that I want to upload.

How to manage html webs after upload file to servlet?

I am developing a web application in which I have an Index.jsp with a form to upload a file to the servlet:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
import="com.uteva.AppWebNieve.ProcesadoExcel"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets" lang="es" xml:lang="es">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>AppWebInformesNieve</title>
</meta>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input value="Subir Excel" type="submit" />
</form>
</body>
</html>
Then I upload correctly the file with my java class:
#Override
protected void doPost(HttpServletRequest
request,HttpServletResponse response) throws ServletException,
IOException{
//***************AQUI MANEJAMOS LA SUBIDA DEL FICHERO LINCES DE INCIDENCIAS***********************
// Get the file location where it would be stored.
//String filePath = getServletContext().getInitParameter("file-upload");
boolean isMultipart;
int maxFileSize = 10000 * 1024;
int maxMemSize = 1000 * 1024;
File file ;
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){ //No se ha podido subir el fichero
/*out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");*/
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 );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet 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();
String 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( filename +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filename +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
System.out.println("Fichero "+filename+" subido correctamente al servidor!!");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}
But after uploading, this open a new simple html which is built in the previously java method by out.println...
The point is, how I can manage this upload to stay in the same html knowing whether the file has been uploaded or not to do some other things with this file? I cannot use get method to upload files and let form action blank...
Or, opening a new html, there must be another way for make a more complex html than using out.println in Java function....
thanks.
Finally I solved it using AJAX following this tutorial: http://www.programming-free.com/2013/06/ajax-file-upload-java-iframe.html

How can I insert a record in the table of mysql from textboxes of html?

I have a jsp file for html and myservlet.java file for Java. I am confused about in which file I will write an insert query either in jsp or Java?.
What is an insert query for netbean?Is it correct?
String query = "INSERT INTO teacher1 (id,name) " + "VALUES (" + 1 + ", '" + aaa + "')";
myservlet.java
class dbconn {
Connection c1 = null;
Statement st = null;
ResultSet rs = null;
private final String ac;
private final String aaa;
dbconn() {
try {
Class.forName("com.mysql.jdbc.Driver");
c1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/teacher", "root", "abcde");
} catch (Exception cnfe) {
System.out.println("Couldn't find the driver!");
System.out.println("Couldn't connect: print out a stack trace and exit.");
System.out.println("We got an exception while creating a statement:" + "that probably means we're no longer connected.");
}
try {
st = (Statement) c1.createStatement();
System.out.println("Statement Created Successfully");
} catch (SQLException se) {
System.out.println("We got an exception while creating a statement:" + "that probably means we're no longer connected.");
}
if (c1 != null) {
System.out.println("Hooray! We connected to the database!");
} else {
System.out.println("We should never get here.");
}
String query = "INSERT INTO teacher1 (id,name) "
+ "VALUES (" + 1 + ", '" + aaa + "')"; // insert query is this
}
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet myservlet</title>");
out.println("</head>");
out.println("<body >");
out.println("<h1>Servlet myservlet at " + request.getContextPath() + "</h1>");
String name = request.getParameter("firstname");
out.println("<h2>" + name + "</h2>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}
}
index.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form action="myservlet" method="GET" >
First name:<br>
<input type="text" name="firstname"/>
<br>
Last name:
<br>
<input type="text" name="lastname" />
<br> <br>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

Why getParameters is returning null when using enctype="multipart/form-data"?

I'm developing a website using spring 4 and Apache Tomcat 7, and I'm having some problems trying to upload an image using inputFile. When I check the parameters in the controller, they are always null.
This is my HTML code:
<form action="product.htm" method="post"
enctype="multipart/form-data">
<p>Product name:</p>
<p style="text-align: left;"><input type = "text" id="productName" name="productName" required="required" /></p>
<p>Product description:</p>
<p style="text-align: left;"><input type = "text" id="productDescription" name="productDescription" /></p>
<p>Product category</p>
<p style="text-align: left;"><select id="productcategory" name="productcategory">
<c:forEach var="item" items="${categories}" varStatus="loop">
<option value="<c:out value="${item.getIdproductCategory()}"/>"><c:out value="${item.getCategory()}"/></option>
</c:forEach>
</select></p>
<p>Select a file to upload:</p>
<input type="file" name="file" size="50" />
<br />
<p style="text-align: left;"><input type="submit" id="submit" name="submit" value="<spring:message code="label.submit"></spring:message>" /></p>
</form>
And this is my controller code:
#Override
public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
ModelAndView mv = new ModelAndView("product");
if (hsr.getParameter("submit") != null) {
insertProduct(hsr);
mv.addObject("send", true);
} else {
mv.addObject("send", false);
}
return mv;
}
public void insertProduct(HttpServletRequest hsr) {
try {
boolean isMultipart;
String filePath;
filePath
= hsr.getServletContext().getInitParameter("file-upload");
int maxFileSize = 50 * 1024;
int maxMemSize = 4 * 1024;
File file;
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("http://localhost:8080/LasDelicias2/resources/images"));
// 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(hsr);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String 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(filePath
+ fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(filePath
+ fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
}
}
} catch (Exception ex) {
System.out.println(ex);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
I found this link: upload servlet
I need to use the parameters because I'm saving some fields in a database.
Thanks for your time.

How to upload files on server folder using jsp [duplicate]

This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 7 years ago.
I am trying to upload some images on folder which locates on my server using servlet/jsp.
Below is my code, which is working on my local machine:
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 1000 * 1024;
private int maxMemSize = 1000 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
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:/Users/puneet verma/Downloads/"));
// 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);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet 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();
String 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( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}
Now my jsp code, where i upload file:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
In My web.xml file, I've included path like this:
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
C:\Users\puneet verma\Downloads\
</param-value>
</context-param>
I've used my server path http://grand-shopping.com/<"some folder"> , but it's not working here at all.
Libraries i'm using are:
commons-fileupload-1.3.jar
commons-io-2.2.jar
Can anyone suggest me , how exactly i need to define my server path, in order to upload images successfully.
Below code is working on my live server as well as in my own Lapy.
Note:
Please Create data folder in WebContent and put in any single image or any file(jsp or html file).
Add jar files
commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
commons-logging-1.0.4.jar
upload.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
UploadServlet.java
package com.servlet;
import java.io.File;
import java.io.IOException;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String DATA_DIRECTORY = "data";
private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
private static final int MAX_REQUEST_SIZE = 1024 * 1024;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);
// Sets the directory used to temporarily store files that are larger
// than the configured size threshold. We use temporary directory for
// java
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("")
+ File.separator + DATA_DIRECTORY;
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println(filePath);
// saves the file to upload directory
item.write(uploadedFile);
}
}
// displays done.jsp page after upload finished
getServletContext().getRequestDispatcher("/done.jsp").forward(
request, response);
} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
web.xml
<servlet>
<description></description>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
done.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>
public class FileUploadExample extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
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 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());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
You cannot upload like this.
http://grand-shopping.com/<"some folder">
You need a physical path exactly like in your local
C:/Users/puneet verma/Downloads/
What you can do is create some local path where your server is working. Hence you can store and retrieve the file. If you bought some domain from any websites there will be path to upload the files. You create these variable as static constant and use it based on the server you are working (Local/Website).
You can only use absolute path
http://grand-shopping.com/<"some folder"> is not an absolute path.
Either you can use a path inside the application which is vurneable
or you can use server specific path like in
windows -> C:/Users/puneet verma/Downloads/
linux -> /opt/Downloads/
I found the similar problem and found the solution and i have blogged about how to upload the file using JSP , In that example i have used the absolute path. Note that if you want to route to some other URL based location you can put a ESB like WSO2 ESB

Categories