How to upload files to server using JSP/Servlet?Convenient way to parse incoming multipart/form-data parameters in a ServletInput TYPE TEXT Value from JSP form (enctype=“multipart/form-data”) returns nullSending additional data with multipartServlet get parameter from multipart form in tomcat 7Multi part upload file servletMultipart/form-data does not support for request.getparamerterFile upload with ServletFileUpload's parseRequest?Error “Unable to process parts as no multi-part configuration has been provided” when uploading fileHow to upload an image and save it in database?null values getting in servlet using request.getParameter from jspMy class is not a servlet error“NoClassDefFoundError: Could not initialize class” errorWhat is the difference between JSF, Servlet and JSP?How to avoid Java code in JSP files?I am unable to call a JSP using RequestDispatcher forwardproblem with file upload in jspwhile calling java method in jsp page, it is showing servlet.service exception nosuchmethodClassNotFound exception with my JSP and servletjava.lang.ClassNotFoundException: org.hibernate.HibernateExceptionWhy data from the servlet is not inserted into sql database?

1980s live-action movie where individually-coloured nations on clouds fight

How can I end combat quickly when the outcome is inevitable?

Rebus with 20 song titles

Group Integers by Originality

Someone whose aspirations exceed abilities or means

Wooden cooking layout

Overlapping String-Blocks

Russian word for a male zebra

Can Rydberg constant be in joules?

Compiling C files on Ubuntu and using the executable on Windows

Alternate way of computing the probability of being dealt a 13 card hand with 3 kings given that you have been dealt 2 kings

You have (3^2 + 2^3 + 2^2) Guesses Left. Figure out the Last one

CROSS APPLY produces outer join

Giant Steps - Coltrane and Slonimsky

SQL counting distinct over partition

How is John Wick 3 a 15 certificate?

What is the actual quality of machine translations?

Arriving at the same result with the opposite hypotheses

Winning Strategy for the Magician and his Apprentice

Certain search in list

How did old MS-DOS games utilize various graphic cards?

Did Milano or Benatar approve or comment on their namesake MCU ships?

Shell script returning "Running: command not found". Not sure why

What is the purpose of the goat for Azazel, as opposed to conventional offerings?



How to upload files to server using JSP/Servlet?


Convenient way to parse incoming multipart/form-data parameters in a ServletInput TYPE TEXT Value from JSP form (enctype=“multipart/form-data”) returns nullSending additional data with multipartServlet get parameter from multipart form in tomcat 7Multi part upload file servletMultipart/form-data does not support for request.getparamerterFile upload with ServletFileUpload's parseRequest?Error “Unable to process parts as no multi-part configuration has been provided” when uploading fileHow to upload an image and save it in database?null values getting in servlet using request.getParameter from jspMy class is not a servlet error“NoClassDefFoundError: Could not initialize class” errorWhat is the difference between JSF, Servlet and JSP?How to avoid Java code in JSP files?I am unable to call a JSP using RequestDispatcher forwardproblem with file upload in jspwhile calling java method in jsp page, it is showing servlet.service exception nosuchmethodClassNotFound exception with my JSP and servletjava.lang.ClassNotFoundException: org.hibernate.HibernateExceptionWhy data from the servlet is not inserted into sql database?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








660















How can I upload files to server using JSP/Servlet? I tried this:



<form action="upload" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>


However, I only get the file name, not the file content. When I add enctype="multipart/form-data" to the <form>, then request.getParameter() returns null.



During research I stumbled upon Apache Common FileUpload. I tried this:



FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.


Unfortunately, the servlet threw an exception without a clear message and cause. Here is the stacktrace:



SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:637)









share|improve this question
























  • Perhaps this article will be helpful: baeldung.com/upload-file-servlet

    – Adam Gerard
    Jan 15 at 4:31

















660















How can I upload files to server using JSP/Servlet? I tried this:



<form action="upload" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>


However, I only get the file name, not the file content. When I add enctype="multipart/form-data" to the <form>, then request.getParameter() returns null.



During research I stumbled upon Apache Common FileUpload. I tried this:



FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.


Unfortunately, the servlet threw an exception without a clear message and cause. Here is the stacktrace:



SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:637)









share|improve this question
























  • Perhaps this article will be helpful: baeldung.com/upload-file-servlet

    – Adam Gerard
    Jan 15 at 4:31













660












660








660


438






How can I upload files to server using JSP/Servlet? I tried this:



<form action="upload" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>


However, I only get the file name, not the file content. When I add enctype="multipart/form-data" to the <form>, then request.getParameter() returns null.



During research I stumbled upon Apache Common FileUpload. I tried this:



FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.


Unfortunately, the servlet threw an exception without a clear message and cause. Here is the stacktrace:



SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:637)









share|improve this question
















How can I upload files to server using JSP/Servlet? I tried this:



<form action="upload" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>


However, I only get the file name, not the file content. When I add enctype="multipart/form-data" to the <form>, then request.getParameter() returns null.



During research I stumbled upon Apache Common FileUpload. I tried this:



FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.


Unfortunately, the servlet threw an exception without a clear message and cause. Here is the stacktrace:



SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:637)






java jsp java-ee servlets file-upload






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 '17 at 16:13









Taryn

196k47299359




196k47299359










asked Mar 11 '10 at 4:07









Thang PhamThang Pham

15.2k69182275




15.2k69182275












  • Perhaps this article will be helpful: baeldung.com/upload-file-servlet

    – Adam Gerard
    Jan 15 at 4:31

















  • Perhaps this article will be helpful: baeldung.com/upload-file-servlet

    – Adam Gerard
    Jan 15 at 4:31
















Perhaps this article will be helpful: baeldung.com/upload-file-servlet

– Adam Gerard
Jan 15 at 4:31





Perhaps this article will be helpful: baeldung.com/upload-file-servlet

– Adam Gerard
Jan 15 at 4:31












12 Answers
12






active

oldest

votes


















1142





+200









Introduction



To browse and select a file for upload you need a HTML <input type="file"> field in the form. As stated in the HTML specification you have to use the POST method and the enctype attribute of the form has to be set to "multipart/form-data".



<form action="upload" method="post" enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>


After submitting such a form, the binary multipart form data is available in the request body in a different format than when the enctype isn't set.



Before Servlet 3.0, the Servlet API didn't natively support multipart/form-data. It supports only the default form enctype of application/x-www-form-urlencoded. The request.getParameter() and consorts would all return null when using multipart form data. This is where the well known Apache Commons FileUpload came into the picture.



Don't manually parse it!



You can in theory parse the request body yourself based on ServletRequest#getInputStream(). However, this is a precise and tedious work which requires precise knowledge of RFC2388. You shouldn't try to do this on your own or copypaste some homegrown library-less code found elsewhere on the Internet. Many online sources have failed hard in this, such as roseindia.net. See also uploading of pdf file. You should rather use a real library which is used (and implicitly tested!) by millions of users for years. Such a library has proven its robustness.



When you're already on Servlet 3.0 or newer, use native API



If you're using at least Servlet 3.0 (Tomcat 7, Jetty 9, JBoss AS 6, GlassFish 3, etc), then you can just use standard API provided HttpServletRequest#getPart() to collect the individual multipart form data items (most Servlet 3.0 implementations actually use Apache Commons FileUpload under the covers for this!). Also, normal form fields are available by getParameter() the usual way.



First annotate your servlet with @MultipartConfig in order to let it recognize and support multipart/form-data requests and thus get getPart() to work:



@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet
// ...



Then, implement its doPost() as follows:



protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
InputStream fileContent = filePart.getInputStream();
// ... (do your job here)



Note the Path#getFileName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



In case you have a <input type="file" name="file" multiple="true" /> for multi-file upload, collect them as below (unfortunately there is no such method as request.getParts("file")):



protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
// ...
List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList()); // Retrieves <input type="file" name="file" multiple="true">

for (Part filePart : fileParts)
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
InputStream fileContent = filePart.getInputStream();
// ... (do your job here)




When you're not on Servlet 3.1 yet, manually get submitted file name



Note that Part#getSubmittedFileName() was introduced in Servlet 3.1 (Tomcat 8, Jetty 9, WildFly 8, GlassFish 4, etc). If you're not on Servlet 3.1 yet, then you need an additional utility method to obtain the submitted file name.



private static String getSubmittedFileName(Part part) 
for (String cd : part.getHeader("content-disposition").split(";"))
if (cd.trim().startsWith("filename"))
String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace(""", "");
return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\') + 1); // MSIE fix.


return null;





String fileName = getSubmittedFileName(filePart);


Note the MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



When you're not on Servlet 3.0 yet, use Apache Commons FileUpload



If you're not on Servlet 3.0 yet (isn't it about time to upgrade?), the common practice is to make use of Apache Commons FileUpload to parse the multpart form data requests. It has an excellent User Guide and FAQ (carefully go through both). There's also the O'Reilly ("cos") MultipartRequest, but it has some (minor) bugs and isn't actively maintained anymore for years. I wouldn't recommend using it. Apache Commons FileUpload is still actively maintained and currently very mature.



In order to use Apache Commons FileUpload, you need to have at least the following files in your webapp's /WEB-INF/lib:




  • commons-fileupload.jar


  • commons-io.jar

Your initial attempt failed most likely because you forgot the commons IO.



Here's a kickoff example how the doPost() of your UploadServlet may look like when using Apache Commons FileUpload:



protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
try
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items)
if (item.isFormField()) etc", select, etc).
String fieldName = item.getFieldName();
String fieldValue = item.getString();
// ... (do your job here)
else
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
// ... (do your job here)


catch (FileUploadException e)
throw new ServletException("Cannot parse multipart request.", e);


// ...



It's very important that you don't call getParameter(), getParameterMap(), getParameterValues(), getInputStream(), getReader(), etc on the same request beforehand. Otherwise the servlet container will read and parse the request body and thus Apache Commons FileUpload will get an empty request body. See also a.o. ServletFileUpload#parseRequest(request) returns an empty list.



Note the FilenameUtils#getName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



Alternatively you can also wrap this all in a Filter which parses it all automagically and put the stuff back in the parametermap of the request so that you can continue using request.getParameter() the usual way and retrieve the uploaded file by request.getAttribute(). You can find an example in this blog article.



Workaround for GlassFish3 bug of getParameter() still returning null



Note that Glassfish versions older than 3.1.2 had a bug wherein the getParameter() still returns null. If you are targeting such a container and can't upgrade it, then you need to extract the value from getPart() with help of this utility method:



private static String getValue(Part part) throws IOException 
BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
StringBuilder value = new StringBuilder();
char[] buffer = new char[1024];
for (int length = 0; (length = reader.read(buffer)) > 0;)
value.append(buffer, 0, length);

return value.toString();





String description = getValue(request.getPart("description")); // Retrieves <input type="text" name="description">


Saving uploaded file (don't use getRealPath() nor part.write()!)



Head to the following answers for detail on properly saving the obtained InputStream (the fileContent variable as shown in the above code snippets) to disk or database:



  • Recommended way to save uploaded files in a servlet application

  • How to upload an image and save it in database?

  • How to convert Part to Blob, so I can store it in MySQL?

Serving uploaded file



Head to the following answers for detail on properly serving the saved file from disk or database back to the client:



  • Load images from outside of webapps / webcontext / deploy folder using <h:graphicImage> or <img> tag

  • How to retrieve and display images from a database in a JSP page?

  • Simplest way to serve static data from outside the application server in a Java web application

  • Abstract template for static resource servlet supporting HTTP caching

Ajaxifying the form



Head to the following answers how to upload using Ajax (and jQuery). Do note that the servlet code to collect the form data does not need to be changed for this! Only the way how you respond may be changed, but this is rather trivial (i.e. instead of forwarding to JSP, just print some JSON or XML or even plain text depending on whatever the script responsible for the Ajax call is expecting).



  • How to upload files to server using JSP/Servlet and Ajax?

  • sending a file as multipart through xmlHttpRequest

  • HTML5 File Upload to Java Servlet


Hope this all helps :)






share|improve this answer

























  • Ah sorry, I was seeing request.getParts("file") and was confused x_x

    – Kagami Sascha Rosylight
    Nov 5 '16 at 22:02











  • With Servlet 3.0, if a MultipartConfig condition is violated (eg: maxFileSize), calling request.getParameter() returns null. Is this on purpose? What if I get some regular (text) parameters before calling getPart (and checking for an IllegalStateException)? This causes a NullPointerException to be thrown before I have a chance to check for the IllegalStateException.

    – theyuv
    Nov 20 '16 at 14:34












  • Please let me know if my question is unclear. Thanks.

    – theyuv
    Nov 20 '16 at 17:30











  • @BalusC I created a post related to this, do you have an idea how I could retrieve extra infos from File API webKitDirectory. More details here stackoverflow.com/questions/45419598/…

    – Rapster
    Jul 31 '17 at 23:52






  • 1





    Yeah, if someone tries to use the code in 3.0 section with tomcat 7, they might face issue in String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.part similar to me

    – raviraja
    Sep 24 '18 at 13:24



















25














If you happen to use Spring MVC, this is how to:
(I'm leaving this here in case someone find it useful).



Use a form with enctype attribute set to "multipart/form-data" (Same as BalusC's Answer)



<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload"/>
</form>


In your controller, map the request parameter file to MultipartFile type as follows:



@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void handleUpload(@RequestParam("file") MultipartFile file) throws IOException
if (!file.isEmpty())
byte[] bytes = file.getBytes(); // alternatively, file.getInputStream();
// application logic




You can get the filename and size using MultipartFile's getOriginalFilename() and getSize().



I've tested this with Spring version 4.1.1.RELEASE.






share|improve this answer























  • If I'm not mistaken, this requires that you configure a bean in your server's application config...

    – Kenny Worden
    Jul 19 '18 at 21:36


















12














You need the common-io.1.4.jar file to be included in your lib directory, or if you're working in any editor, like NetBeans, then you need to go to project properties and just add the JAR file and you will be done.



To get the common.io.jar file just google it or just go to the Apache Tomcat website where you get the option for a free download of this file. But remember one thing: download the binary ZIP file if you're a Windows user.






share|improve this answer

























  • Can't find .jar but .zip. Do you mean .zip?

    – Malwinder Singh
    Oct 9 '14 at 11:42


















9














I am Using common Servlet for every Html Form whether it has attachments or not.
This Servlet returns a TreeMap where the keys are jsp name Parameters and values are User Inputs and saves all attachments in fixed directory and later you rename the directory of your choice.Here Connections is our custom interface having connection object. I think this will help you



public class ServletCommonfunctions extends HttpServlet implements
Connections

private static final long serialVersionUID = 1L;

public ServletCommonfunctions()

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException

public SortedMap<String, String> savefilesindirectory(
HttpServletRequest request, HttpServletResponse response)
throws IOException
// Map<String, String> key_values = Collections.synchronizedMap( new
// TreeMap<String, String>());
SortedMap<String, String> key_values = new TreeMap<String, String>();
String dist = null, fact = null;
PrintWriter out = response.getWriter();
File file;
String filePath = "E:\FSPATH1\2KL06CS048\";
System.out.println("Directory Created ????????????"
+ new File(filePath).mkdir());
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0))
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(filePath));
// 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.
@SuppressWarnings("unchecked")
List<FileItem> fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator<FileItem> i = fileItems.iterator();
while (i.hasNext())
FileItem fi = (FileItem) i.next();
if (!fi.isFormField())
// Get the uploaded file parameters
String fileName = fi.getName();
// 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);
else
key_values.put(fi.getFieldName(), fi.getString());


catch (Exception ex)
System.out.println(ex);


return key_values;







share|improve this answer

























  • @buhake sindi hey what should be the filepath if i m using live server or i live my project by uploading files to the server

    – AmanS
    Oct 20 '13 at 4:00






  • 2





    Any directory in live server.if you write a code to create a directory in servlet then directory will be created in live srver

    – feel good and programming
    Oct 20 '13 at 9:27


















8














Without component or external Library in Tomcat 6 o 7



Enabling Upload in the web.xml file:



http://joseluisbz.wordpress.com/2014/01/17/manually-installing-php-tomcat-and-httpd-lounge/#Enabling%20File%20Uploads.



<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<multipart-config>
<max-file-size>3145728</max-file-size>
<max-request-size>5242880</max-request-size>
</multipart-config>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>


AS YOU CAN SEE:



 <multipart-config>
<max-file-size>3145728</max-file-size>
<max-request-size>5242880</max-request-size>
</multipart-config>


Uploading Files using JSP. Files:



In the html file



<form method="post" enctype="multipart/form-data" name="Form" >

<input type="file" name="fFoto" id="fFoto" value="" /></td>
<input type="file" name="fResumen" id="fResumen" value=""/>


In the JSP File or Servlet



 InputStream isFoto = request.getPart("fFoto").getInputStream();
InputStream isResu = request.getPart("fResumen").getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buf[] = new byte[8192];
int qt = 0;
while ((qt = isResu.read(buf)) != -1)
baos.write(buf, 0, qt);

String sResumen = baos.toString();


Edit your code to servlet requirements, like max-file-size, max-request-size and other options that you can to set...






share|improve this answer






























    8














    For Spring MVC
    I have been trying for hours to do this
    and managed to have a simpler version that worked for taking form input both data and image.



    <form action="/handleform" method="post" enctype="multipart/form-data">
    <input type="text" name="name" />
    <input type="text" name="age" />
    <input type="file" name="file" />
    <input type="submit" />
    </form>


    Controller to handle



    @Controller
    public class FormController
    @RequestMapping(value="/handleform",method= RequestMethod.POST)
    ModelAndView register(@RequestParam String name, @RequestParam int age, @RequestParam MultipartFile file)
    throws ServletException, IOException

    System.out.println(name);
    System.out.println(age);
    if(!file.isEmpty())
    byte[] bytes = file.getBytes();
    String filename = file.getOriginalFilename();
    BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("D:/" + filename)));
    stream.write(bytes);
    stream.flush();
    stream.close();

    return new ModelAndView("index");




    Hope it helps :)






    share|improve this answer























    • Can you please share select image form db mysql and show it on jsp/html?

      – Ved Prakash
      Mar 13 at 12:27


















    6














    Another source of this problem occurs if you are using Geronimo with its embedded Tomcat. In this case, after many iterations of testing commons-io and commons-fileupload, the problem arises from a parent classloader handling the commons-xxx jars. This has to be prevented. The crash always occurred at:



    fileItems = uploader.parseRequest(request);


    Note that the List type of fileItems has changed with the current version of commons-fileupload to be specifically List<FileItem> as opposed to prior versions where it was generic List.



    I added the source code for commons-fileupload and commons-io into my Eclipse project to trace the actual error and finally got some insight. First, the exception thrown is of type Throwable not the stated FileIOException nor even Exception (these will not be trapped). Second, the error message is obfuscatory in that it stated class not found because axis2 could not find commons-io. Axis2 is not used in my project at all but exists as a folder in the Geronimo repository subdirectory as part of standard installation.



    Finally, I found 1 place that posed a working solution which successfully solved my problem. You must hide the jars from parent loader in the deployment plan. This was put into geronimo-web.xml with my full file shown below.



    Pasted from <http://osdir.com/ml/user-geronimo-apache/2011-03/msg00026.html> 



    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:pers="http://java.sun.com/xml/ns/persistence" xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1">
    <dep:environment>
    <dep:moduleId>
    <dep:groupId>DataStar</dep:groupId>
    <dep:artifactId>DataStar</dep:artifactId>
    <dep:version>1.0</dep:version>
    <dep:type>car</dep:type>
    </dep:moduleId>

    <!--Don't load commons-io or fileupload from parent classloaders-->
    <dep:hidden-classes>
    <dep:filter>org.apache.commons.io</dep:filter>
    <dep:filter>org.apache.commons.fileupload</dep:filter>
    </dep:hidden-classes>
    <dep:inverse-classloading/>


    </dep:environment>
    <web:context-root>/DataStar</web:context-root>
    </web:web-app>





    share|improve this answer






























      0














      Here's an example using apache commons-fileupload:



      // apache commons-fileupload to handle file upload
      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setRepository(new File(DataSources.TORRENTS_DIR()));
      ServletFileUpload fileUpload = new ServletFileUpload(factory);

      List<FileItem> items = fileUpload.parseRequest(req.raw());
      FileItem item = items.stream()
      .filter(e ->
      "the_upload_name".equals(e.getFieldName()))
      .findFirst().get();
      String fileName = item.getName();

      item.write(new File(dir, fileName));
      log.info(fileName);





      share|improve this answer






























        -1














        you can upload file using jsp /servlet.



        <form action="UploadFileServlet" method="post">
        <input type="text" name="description" />
        <input type="file" name="file" />
        <input type="submit" />
        </form>


        on the other hand server side.
        use following code.



         package com.abc..servlet;

        import java.io.File;
        ---------
        --------


        /**
        * Servlet implementation class UploadFileServlet
        */
        public class UploadFileServlet extends HttpServlet
        private static final long serialVersionUID = 1L;

        public UploadFileServlet()
        super();
        // TODO Auto-generated constructor stub

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        // TODO Auto-generated method stub
        response.sendRedirect("../jsp/ErrorPage.jsp");


        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        // TODO Auto-generated method stub

        PrintWriter out = response.getWriter();
        HttpSession httpSession = request.getSession();
        String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;

        String path1 = filePathUpload;
        String filename = null;
        File path = null;
        FileItem item=null;


        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart)
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        String FieldName = "";
        try
        List items = upload.parseRequest(request);
        Iterator iterator = items.iterator();
        while (iterator.hasNext())
        item = (FileItem) iterator.next();

        if (fieldname.equals("description"))
        description = item.getString();


        if (!item.isFormField())
        filename = item.getName();
        path = new File(path1 + File.separator);
        if (!path.exists())
        boolean status = path.mkdirs();

        /* START OF CODE FRO PRIVILEDGE*/

        File uploadedFile = new File(path + Filename); // for copy file
        item.write(uploadedFile);

        else
        f1 = item.getName();


        // END OF WHILE
        response.sendRedirect("welcome.jsp");
        catch (FileUploadException e)
        e.printStackTrace();
        catch (Exception e)
        e.printStackTrace();


        }

        }





        share|improve this answer






























          -1














          DiskFileUpload upload=new DiskFileUpload();


          From this object you have to get file items and fields then yo can store into server like followed:



          String loc="./webapps/prjct name/server folder/"+contentid+extension;
          File uploadFile=new File(loc);
          item.write(uploadFile);





          share|improve this answer
































            -2














            Sending multiple file for file we have to use enctype="multipart/form-data"

            and to send multiple file use multiple="multiple" in input tag



            <form action="upload" method="post" enctype="multipart/form-data">
            <input type="file" name="fileattachments" multiple="multiple"/>
            <input type="submit" />
            </form>





            share|improve this answer




















            • 2





              How would we go about doing getPart("fileattachments") so we get an array of Parts instead? I don't think getPart for multiple files will work?

              – CyberMew
              Sep 29 '15 at 6:38


















            -2














            HTML PAGE



            <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>


            SERVLET FILE



            // Import required java libraries
            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 = 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( 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.");




            web.xml



            Compile above servlet UploadServlet and create required entry in web.xml file as follows.



            <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>





            share|improve this answer























              protected by BalusC May 20 '12 at 12:44



              Thank you for your interest in this question.
              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



              Would you like to answer one of these unanswered questions instead?














              12 Answers
              12






              active

              oldest

              votes








              12 Answers
              12






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1142





              +200









              Introduction



              To browse and select a file for upload you need a HTML <input type="file"> field in the form. As stated in the HTML specification you have to use the POST method and the enctype attribute of the form has to be set to "multipart/form-data".



              <form action="upload" method="post" enctype="multipart/form-data">
              <input type="text" name="description" />
              <input type="file" name="file" />
              <input type="submit" />
              </form>


              After submitting such a form, the binary multipart form data is available in the request body in a different format than when the enctype isn't set.



              Before Servlet 3.0, the Servlet API didn't natively support multipart/form-data. It supports only the default form enctype of application/x-www-form-urlencoded. The request.getParameter() and consorts would all return null when using multipart form data. This is where the well known Apache Commons FileUpload came into the picture.



              Don't manually parse it!



              You can in theory parse the request body yourself based on ServletRequest#getInputStream(). However, this is a precise and tedious work which requires precise knowledge of RFC2388. You shouldn't try to do this on your own or copypaste some homegrown library-less code found elsewhere on the Internet. Many online sources have failed hard in this, such as roseindia.net. See also uploading of pdf file. You should rather use a real library which is used (and implicitly tested!) by millions of users for years. Such a library has proven its robustness.



              When you're already on Servlet 3.0 or newer, use native API



              If you're using at least Servlet 3.0 (Tomcat 7, Jetty 9, JBoss AS 6, GlassFish 3, etc), then you can just use standard API provided HttpServletRequest#getPart() to collect the individual multipart form data items (most Servlet 3.0 implementations actually use Apache Commons FileUpload under the covers for this!). Also, normal form fields are available by getParameter() the usual way.



              First annotate your servlet with @MultipartConfig in order to let it recognize and support multipart/form-data requests and thus get getPart() to work:



              @WebServlet("/upload")
              @MultipartConfig
              public class UploadServlet extends HttpServlet
              // ...



              Then, implement its doPost() as follows:



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
              Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
              String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
              InputStream fileContent = filePart.getInputStream();
              // ... (do your job here)



              Note the Path#getFileName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              In case you have a <input type="file" name="file" multiple="true" /> for multi-file upload, collect them as below (unfortunately there is no such method as request.getParts("file")):



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              // ...
              List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList()); // Retrieves <input type="file" name="file" multiple="true">

              for (Part filePart : fileParts)
              String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
              InputStream fileContent = filePart.getInputStream();
              // ... (do your job here)




              When you're not on Servlet 3.1 yet, manually get submitted file name



              Note that Part#getSubmittedFileName() was introduced in Servlet 3.1 (Tomcat 8, Jetty 9, WildFly 8, GlassFish 4, etc). If you're not on Servlet 3.1 yet, then you need an additional utility method to obtain the submitted file name.



              private static String getSubmittedFileName(Part part) 
              for (String cd : part.getHeader("content-disposition").split(";"))
              if (cd.trim().startsWith("filename"))
              String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace(""", "");
              return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\') + 1); // MSIE fix.


              return null;





              String fileName = getSubmittedFileName(filePart);


              Note the MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              When you're not on Servlet 3.0 yet, use Apache Commons FileUpload



              If you're not on Servlet 3.0 yet (isn't it about time to upgrade?), the common practice is to make use of Apache Commons FileUpload to parse the multpart form data requests. It has an excellent User Guide and FAQ (carefully go through both). There's also the O'Reilly ("cos") MultipartRequest, but it has some (minor) bugs and isn't actively maintained anymore for years. I wouldn't recommend using it. Apache Commons FileUpload is still actively maintained and currently very mature.



              In order to use Apache Commons FileUpload, you need to have at least the following files in your webapp's /WEB-INF/lib:




              • commons-fileupload.jar


              • commons-io.jar

              Your initial attempt failed most likely because you forgot the commons IO.



              Here's a kickoff example how the doPost() of your UploadServlet may look like when using Apache Commons FileUpload:



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              try
              List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
              for (FileItem item : items)
              if (item.isFormField()) etc", select, etc).
              String fieldName = item.getFieldName();
              String fieldValue = item.getString();
              // ... (do your job here)
              else
              // Process form file field (input type="file").
              String fieldName = item.getFieldName();
              String fileName = FilenameUtils.getName(item.getName());
              InputStream fileContent = item.getInputStream();
              // ... (do your job here)


              catch (FileUploadException e)
              throw new ServletException("Cannot parse multipart request.", e);


              // ...



              It's very important that you don't call getParameter(), getParameterMap(), getParameterValues(), getInputStream(), getReader(), etc on the same request beforehand. Otherwise the servlet container will read and parse the request body and thus Apache Commons FileUpload will get an empty request body. See also a.o. ServletFileUpload#parseRequest(request) returns an empty list.



              Note the FilenameUtils#getName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              Alternatively you can also wrap this all in a Filter which parses it all automagically and put the stuff back in the parametermap of the request so that you can continue using request.getParameter() the usual way and retrieve the uploaded file by request.getAttribute(). You can find an example in this blog article.



              Workaround for GlassFish3 bug of getParameter() still returning null



              Note that Glassfish versions older than 3.1.2 had a bug wherein the getParameter() still returns null. If you are targeting such a container and can't upgrade it, then you need to extract the value from getPart() with help of this utility method:



              private static String getValue(Part part) throws IOException 
              BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
              StringBuilder value = new StringBuilder();
              char[] buffer = new char[1024];
              for (int length = 0; (length = reader.read(buffer)) > 0;)
              value.append(buffer, 0, length);

              return value.toString();





              String description = getValue(request.getPart("description")); // Retrieves <input type="text" name="description">


              Saving uploaded file (don't use getRealPath() nor part.write()!)



              Head to the following answers for detail on properly saving the obtained InputStream (the fileContent variable as shown in the above code snippets) to disk or database:



              • Recommended way to save uploaded files in a servlet application

              • How to upload an image and save it in database?

              • How to convert Part to Blob, so I can store it in MySQL?

              Serving uploaded file



              Head to the following answers for detail on properly serving the saved file from disk or database back to the client:



              • Load images from outside of webapps / webcontext / deploy folder using <h:graphicImage> or <img> tag

              • How to retrieve and display images from a database in a JSP page?

              • Simplest way to serve static data from outside the application server in a Java web application

              • Abstract template for static resource servlet supporting HTTP caching

              Ajaxifying the form



              Head to the following answers how to upload using Ajax (and jQuery). Do note that the servlet code to collect the form data does not need to be changed for this! Only the way how you respond may be changed, but this is rather trivial (i.e. instead of forwarding to JSP, just print some JSON or XML or even plain text depending on whatever the script responsible for the Ajax call is expecting).



              • How to upload files to server using JSP/Servlet and Ajax?

              • sending a file as multipart through xmlHttpRequest

              • HTML5 File Upload to Java Servlet


              Hope this all helps :)






              share|improve this answer

























              • Ah sorry, I was seeing request.getParts("file") and was confused x_x

                – Kagami Sascha Rosylight
                Nov 5 '16 at 22:02











              • With Servlet 3.0, if a MultipartConfig condition is violated (eg: maxFileSize), calling request.getParameter() returns null. Is this on purpose? What if I get some regular (text) parameters before calling getPart (and checking for an IllegalStateException)? This causes a NullPointerException to be thrown before I have a chance to check for the IllegalStateException.

                – theyuv
                Nov 20 '16 at 14:34












              • Please let me know if my question is unclear. Thanks.

                – theyuv
                Nov 20 '16 at 17:30











              • @BalusC I created a post related to this, do you have an idea how I could retrieve extra infos from File API webKitDirectory. More details here stackoverflow.com/questions/45419598/…

                – Rapster
                Jul 31 '17 at 23:52






              • 1





                Yeah, if someone tries to use the code in 3.0 section with tomcat 7, they might face issue in String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.part similar to me

                – raviraja
                Sep 24 '18 at 13:24
















              1142





              +200









              Introduction



              To browse and select a file for upload you need a HTML <input type="file"> field in the form. As stated in the HTML specification you have to use the POST method and the enctype attribute of the form has to be set to "multipart/form-data".



              <form action="upload" method="post" enctype="multipart/form-data">
              <input type="text" name="description" />
              <input type="file" name="file" />
              <input type="submit" />
              </form>


              After submitting such a form, the binary multipart form data is available in the request body in a different format than when the enctype isn't set.



              Before Servlet 3.0, the Servlet API didn't natively support multipart/form-data. It supports only the default form enctype of application/x-www-form-urlencoded. The request.getParameter() and consorts would all return null when using multipart form data. This is where the well known Apache Commons FileUpload came into the picture.



              Don't manually parse it!



              You can in theory parse the request body yourself based on ServletRequest#getInputStream(). However, this is a precise and tedious work which requires precise knowledge of RFC2388. You shouldn't try to do this on your own or copypaste some homegrown library-less code found elsewhere on the Internet. Many online sources have failed hard in this, such as roseindia.net. See also uploading of pdf file. You should rather use a real library which is used (and implicitly tested!) by millions of users for years. Such a library has proven its robustness.



              When you're already on Servlet 3.0 or newer, use native API



              If you're using at least Servlet 3.0 (Tomcat 7, Jetty 9, JBoss AS 6, GlassFish 3, etc), then you can just use standard API provided HttpServletRequest#getPart() to collect the individual multipart form data items (most Servlet 3.0 implementations actually use Apache Commons FileUpload under the covers for this!). Also, normal form fields are available by getParameter() the usual way.



              First annotate your servlet with @MultipartConfig in order to let it recognize and support multipart/form-data requests and thus get getPart() to work:



              @WebServlet("/upload")
              @MultipartConfig
              public class UploadServlet extends HttpServlet
              // ...



              Then, implement its doPost() as follows:



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
              Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
              String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
              InputStream fileContent = filePart.getInputStream();
              // ... (do your job here)



              Note the Path#getFileName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              In case you have a <input type="file" name="file" multiple="true" /> for multi-file upload, collect them as below (unfortunately there is no such method as request.getParts("file")):



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              // ...
              List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList()); // Retrieves <input type="file" name="file" multiple="true">

              for (Part filePart : fileParts)
              String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
              InputStream fileContent = filePart.getInputStream();
              // ... (do your job here)




              When you're not on Servlet 3.1 yet, manually get submitted file name



              Note that Part#getSubmittedFileName() was introduced in Servlet 3.1 (Tomcat 8, Jetty 9, WildFly 8, GlassFish 4, etc). If you're not on Servlet 3.1 yet, then you need an additional utility method to obtain the submitted file name.



              private static String getSubmittedFileName(Part part) 
              for (String cd : part.getHeader("content-disposition").split(";"))
              if (cd.trim().startsWith("filename"))
              String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace(""", "");
              return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\') + 1); // MSIE fix.


              return null;





              String fileName = getSubmittedFileName(filePart);


              Note the MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              When you're not on Servlet 3.0 yet, use Apache Commons FileUpload



              If you're not on Servlet 3.0 yet (isn't it about time to upgrade?), the common practice is to make use of Apache Commons FileUpload to parse the multpart form data requests. It has an excellent User Guide and FAQ (carefully go through both). There's also the O'Reilly ("cos") MultipartRequest, but it has some (minor) bugs and isn't actively maintained anymore for years. I wouldn't recommend using it. Apache Commons FileUpload is still actively maintained and currently very mature.



              In order to use Apache Commons FileUpload, you need to have at least the following files in your webapp's /WEB-INF/lib:




              • commons-fileupload.jar


              • commons-io.jar

              Your initial attempt failed most likely because you forgot the commons IO.



              Here's a kickoff example how the doPost() of your UploadServlet may look like when using Apache Commons FileUpload:



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              try
              List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
              for (FileItem item : items)
              if (item.isFormField()) etc", select, etc).
              String fieldName = item.getFieldName();
              String fieldValue = item.getString();
              // ... (do your job here)
              else
              // Process form file field (input type="file").
              String fieldName = item.getFieldName();
              String fileName = FilenameUtils.getName(item.getName());
              InputStream fileContent = item.getInputStream();
              // ... (do your job here)


              catch (FileUploadException e)
              throw new ServletException("Cannot parse multipart request.", e);


              // ...



              It's very important that you don't call getParameter(), getParameterMap(), getParameterValues(), getInputStream(), getReader(), etc on the same request beforehand. Otherwise the servlet container will read and parse the request body and thus Apache Commons FileUpload will get an empty request body. See also a.o. ServletFileUpload#parseRequest(request) returns an empty list.



              Note the FilenameUtils#getName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              Alternatively you can also wrap this all in a Filter which parses it all automagically and put the stuff back in the parametermap of the request so that you can continue using request.getParameter() the usual way and retrieve the uploaded file by request.getAttribute(). You can find an example in this blog article.



              Workaround for GlassFish3 bug of getParameter() still returning null



              Note that Glassfish versions older than 3.1.2 had a bug wherein the getParameter() still returns null. If you are targeting such a container and can't upgrade it, then you need to extract the value from getPart() with help of this utility method:



              private static String getValue(Part part) throws IOException 
              BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
              StringBuilder value = new StringBuilder();
              char[] buffer = new char[1024];
              for (int length = 0; (length = reader.read(buffer)) > 0;)
              value.append(buffer, 0, length);

              return value.toString();





              String description = getValue(request.getPart("description")); // Retrieves <input type="text" name="description">


              Saving uploaded file (don't use getRealPath() nor part.write()!)



              Head to the following answers for detail on properly saving the obtained InputStream (the fileContent variable as shown in the above code snippets) to disk or database:



              • Recommended way to save uploaded files in a servlet application

              • How to upload an image and save it in database?

              • How to convert Part to Blob, so I can store it in MySQL?

              Serving uploaded file



              Head to the following answers for detail on properly serving the saved file from disk or database back to the client:



              • Load images from outside of webapps / webcontext / deploy folder using <h:graphicImage> or <img> tag

              • How to retrieve and display images from a database in a JSP page?

              • Simplest way to serve static data from outside the application server in a Java web application

              • Abstract template for static resource servlet supporting HTTP caching

              Ajaxifying the form



              Head to the following answers how to upload using Ajax (and jQuery). Do note that the servlet code to collect the form data does not need to be changed for this! Only the way how you respond may be changed, but this is rather trivial (i.e. instead of forwarding to JSP, just print some JSON or XML or even plain text depending on whatever the script responsible for the Ajax call is expecting).



              • How to upload files to server using JSP/Servlet and Ajax?

              • sending a file as multipart through xmlHttpRequest

              • HTML5 File Upload to Java Servlet


              Hope this all helps :)






              share|improve this answer

























              • Ah sorry, I was seeing request.getParts("file") and was confused x_x

                – Kagami Sascha Rosylight
                Nov 5 '16 at 22:02











              • With Servlet 3.0, if a MultipartConfig condition is violated (eg: maxFileSize), calling request.getParameter() returns null. Is this on purpose? What if I get some regular (text) parameters before calling getPart (and checking for an IllegalStateException)? This causes a NullPointerException to be thrown before I have a chance to check for the IllegalStateException.

                – theyuv
                Nov 20 '16 at 14:34












              • Please let me know if my question is unclear. Thanks.

                – theyuv
                Nov 20 '16 at 17:30











              • @BalusC I created a post related to this, do you have an idea how I could retrieve extra infos from File API webKitDirectory. More details here stackoverflow.com/questions/45419598/…

                – Rapster
                Jul 31 '17 at 23:52






              • 1





                Yeah, if someone tries to use the code in 3.0 section with tomcat 7, they might face issue in String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.part similar to me

                – raviraja
                Sep 24 '18 at 13:24














              1142





              +200







              1142





              +200



              1142




              +200





              Introduction



              To browse and select a file for upload you need a HTML <input type="file"> field in the form. As stated in the HTML specification you have to use the POST method and the enctype attribute of the form has to be set to "multipart/form-data".



              <form action="upload" method="post" enctype="multipart/form-data">
              <input type="text" name="description" />
              <input type="file" name="file" />
              <input type="submit" />
              </form>


              After submitting such a form, the binary multipart form data is available in the request body in a different format than when the enctype isn't set.



              Before Servlet 3.0, the Servlet API didn't natively support multipart/form-data. It supports only the default form enctype of application/x-www-form-urlencoded. The request.getParameter() and consorts would all return null when using multipart form data. This is where the well known Apache Commons FileUpload came into the picture.



              Don't manually parse it!



              You can in theory parse the request body yourself based on ServletRequest#getInputStream(). However, this is a precise and tedious work which requires precise knowledge of RFC2388. You shouldn't try to do this on your own or copypaste some homegrown library-less code found elsewhere on the Internet. Many online sources have failed hard in this, such as roseindia.net. See also uploading of pdf file. You should rather use a real library which is used (and implicitly tested!) by millions of users for years. Such a library has proven its robustness.



              When you're already on Servlet 3.0 or newer, use native API



              If you're using at least Servlet 3.0 (Tomcat 7, Jetty 9, JBoss AS 6, GlassFish 3, etc), then you can just use standard API provided HttpServletRequest#getPart() to collect the individual multipart form data items (most Servlet 3.0 implementations actually use Apache Commons FileUpload under the covers for this!). Also, normal form fields are available by getParameter() the usual way.



              First annotate your servlet with @MultipartConfig in order to let it recognize and support multipart/form-data requests and thus get getPart() to work:



              @WebServlet("/upload")
              @MultipartConfig
              public class UploadServlet extends HttpServlet
              // ...



              Then, implement its doPost() as follows:



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
              Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
              String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
              InputStream fileContent = filePart.getInputStream();
              // ... (do your job here)



              Note the Path#getFileName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              In case you have a <input type="file" name="file" multiple="true" /> for multi-file upload, collect them as below (unfortunately there is no such method as request.getParts("file")):



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              // ...
              List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList()); // Retrieves <input type="file" name="file" multiple="true">

              for (Part filePart : fileParts)
              String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
              InputStream fileContent = filePart.getInputStream();
              // ... (do your job here)




              When you're not on Servlet 3.1 yet, manually get submitted file name



              Note that Part#getSubmittedFileName() was introduced in Servlet 3.1 (Tomcat 8, Jetty 9, WildFly 8, GlassFish 4, etc). If you're not on Servlet 3.1 yet, then you need an additional utility method to obtain the submitted file name.



              private static String getSubmittedFileName(Part part) 
              for (String cd : part.getHeader("content-disposition").split(";"))
              if (cd.trim().startsWith("filename"))
              String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace(""", "");
              return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\') + 1); // MSIE fix.


              return null;





              String fileName = getSubmittedFileName(filePart);


              Note the MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              When you're not on Servlet 3.0 yet, use Apache Commons FileUpload



              If you're not on Servlet 3.0 yet (isn't it about time to upgrade?), the common practice is to make use of Apache Commons FileUpload to parse the multpart form data requests. It has an excellent User Guide and FAQ (carefully go through both). There's also the O'Reilly ("cos") MultipartRequest, but it has some (minor) bugs and isn't actively maintained anymore for years. I wouldn't recommend using it. Apache Commons FileUpload is still actively maintained and currently very mature.



              In order to use Apache Commons FileUpload, you need to have at least the following files in your webapp's /WEB-INF/lib:




              • commons-fileupload.jar


              • commons-io.jar

              Your initial attempt failed most likely because you forgot the commons IO.



              Here's a kickoff example how the doPost() of your UploadServlet may look like when using Apache Commons FileUpload:



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              try
              List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
              for (FileItem item : items)
              if (item.isFormField()) etc", select, etc).
              String fieldName = item.getFieldName();
              String fieldValue = item.getString();
              // ... (do your job here)
              else
              // Process form file field (input type="file").
              String fieldName = item.getFieldName();
              String fileName = FilenameUtils.getName(item.getName());
              InputStream fileContent = item.getInputStream();
              // ... (do your job here)


              catch (FileUploadException e)
              throw new ServletException("Cannot parse multipart request.", e);


              // ...



              It's very important that you don't call getParameter(), getParameterMap(), getParameterValues(), getInputStream(), getReader(), etc on the same request beforehand. Otherwise the servlet container will read and parse the request body and thus Apache Commons FileUpload will get an empty request body. See also a.o. ServletFileUpload#parseRequest(request) returns an empty list.



              Note the FilenameUtils#getName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              Alternatively you can also wrap this all in a Filter which parses it all automagically and put the stuff back in the parametermap of the request so that you can continue using request.getParameter() the usual way and retrieve the uploaded file by request.getAttribute(). You can find an example in this blog article.



              Workaround for GlassFish3 bug of getParameter() still returning null



              Note that Glassfish versions older than 3.1.2 had a bug wherein the getParameter() still returns null. If you are targeting such a container and can't upgrade it, then you need to extract the value from getPart() with help of this utility method:



              private static String getValue(Part part) throws IOException 
              BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
              StringBuilder value = new StringBuilder();
              char[] buffer = new char[1024];
              for (int length = 0; (length = reader.read(buffer)) > 0;)
              value.append(buffer, 0, length);

              return value.toString();





              String description = getValue(request.getPart("description")); // Retrieves <input type="text" name="description">


              Saving uploaded file (don't use getRealPath() nor part.write()!)



              Head to the following answers for detail on properly saving the obtained InputStream (the fileContent variable as shown in the above code snippets) to disk or database:



              • Recommended way to save uploaded files in a servlet application

              • How to upload an image and save it in database?

              • How to convert Part to Blob, so I can store it in MySQL?

              Serving uploaded file



              Head to the following answers for detail on properly serving the saved file from disk or database back to the client:



              • Load images from outside of webapps / webcontext / deploy folder using <h:graphicImage> or <img> tag

              • How to retrieve and display images from a database in a JSP page?

              • Simplest way to serve static data from outside the application server in a Java web application

              • Abstract template for static resource servlet supporting HTTP caching

              Ajaxifying the form



              Head to the following answers how to upload using Ajax (and jQuery). Do note that the servlet code to collect the form data does not need to be changed for this! Only the way how you respond may be changed, but this is rather trivial (i.e. instead of forwarding to JSP, just print some JSON or XML or even plain text depending on whatever the script responsible for the Ajax call is expecting).



              • How to upload files to server using JSP/Servlet and Ajax?

              • sending a file as multipart through xmlHttpRequest

              • HTML5 File Upload to Java Servlet


              Hope this all helps :)






              share|improve this answer















              Introduction



              To browse and select a file for upload you need a HTML <input type="file"> field in the form. As stated in the HTML specification you have to use the POST method and the enctype attribute of the form has to be set to "multipart/form-data".



              <form action="upload" method="post" enctype="multipart/form-data">
              <input type="text" name="description" />
              <input type="file" name="file" />
              <input type="submit" />
              </form>


              After submitting such a form, the binary multipart form data is available in the request body in a different format than when the enctype isn't set.



              Before Servlet 3.0, the Servlet API didn't natively support multipart/form-data. It supports only the default form enctype of application/x-www-form-urlencoded. The request.getParameter() and consorts would all return null when using multipart form data. This is where the well known Apache Commons FileUpload came into the picture.



              Don't manually parse it!



              You can in theory parse the request body yourself based on ServletRequest#getInputStream(). However, this is a precise and tedious work which requires precise knowledge of RFC2388. You shouldn't try to do this on your own or copypaste some homegrown library-less code found elsewhere on the Internet. Many online sources have failed hard in this, such as roseindia.net. See also uploading of pdf file. You should rather use a real library which is used (and implicitly tested!) by millions of users for years. Such a library has proven its robustness.



              When you're already on Servlet 3.0 or newer, use native API



              If you're using at least Servlet 3.0 (Tomcat 7, Jetty 9, JBoss AS 6, GlassFish 3, etc), then you can just use standard API provided HttpServletRequest#getPart() to collect the individual multipart form data items (most Servlet 3.0 implementations actually use Apache Commons FileUpload under the covers for this!). Also, normal form fields are available by getParameter() the usual way.



              First annotate your servlet with @MultipartConfig in order to let it recognize and support multipart/form-data requests and thus get getPart() to work:



              @WebServlet("/upload")
              @MultipartConfig
              public class UploadServlet extends HttpServlet
              // ...



              Then, implement its doPost() as follows:



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
              Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
              String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
              InputStream fileContent = filePart.getInputStream();
              // ... (do your job here)



              Note the Path#getFileName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              In case you have a <input type="file" name="file" multiple="true" /> for multi-file upload, collect them as below (unfortunately there is no such method as request.getParts("file")):



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              // ...
              List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList()); // Retrieves <input type="file" name="file" multiple="true">

              for (Part filePart : fileParts)
              String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
              InputStream fileContent = filePart.getInputStream();
              // ... (do your job here)




              When you're not on Servlet 3.1 yet, manually get submitted file name



              Note that Part#getSubmittedFileName() was introduced in Servlet 3.1 (Tomcat 8, Jetty 9, WildFly 8, GlassFish 4, etc). If you're not on Servlet 3.1 yet, then you need an additional utility method to obtain the submitted file name.



              private static String getSubmittedFileName(Part part) 
              for (String cd : part.getHeader("content-disposition").split(";"))
              if (cd.trim().startsWith("filename"))
              String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace(""", "");
              return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\') + 1); // MSIE fix.


              return null;





              String fileName = getSubmittedFileName(filePart);


              Note the MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              When you're not on Servlet 3.0 yet, use Apache Commons FileUpload



              If you're not on Servlet 3.0 yet (isn't it about time to upgrade?), the common practice is to make use of Apache Commons FileUpload to parse the multpart form data requests. It has an excellent User Guide and FAQ (carefully go through both). There's also the O'Reilly ("cos") MultipartRequest, but it has some (minor) bugs and isn't actively maintained anymore for years. I wouldn't recommend using it. Apache Commons FileUpload is still actively maintained and currently very mature.



              In order to use Apache Commons FileUpload, you need to have at least the following files in your webapp's /WEB-INF/lib:




              • commons-fileupload.jar


              • commons-io.jar

              Your initial attempt failed most likely because you forgot the commons IO.



              Here's a kickoff example how the doPost() of your UploadServlet may look like when using Apache Commons FileUpload:



              protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
              try
              List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
              for (FileItem item : items)
              if (item.isFormField()) etc", select, etc).
              String fieldName = item.getFieldName();
              String fieldValue = item.getString();
              // ... (do your job here)
              else
              // Process form file field (input type="file").
              String fieldName = item.getFieldName();
              String fileName = FilenameUtils.getName(item.getName());
              InputStream fileContent = item.getInputStream();
              // ... (do your job here)


              catch (FileUploadException e)
              throw new ServletException("Cannot parse multipart request.", e);


              // ...



              It's very important that you don't call getParameter(), getParameterMap(), getParameterValues(), getInputStream(), getReader(), etc on the same request beforehand. Otherwise the servlet container will read and parse the request body and thus Apache Commons FileUpload will get an empty request body. See also a.o. ServletFileUpload#parseRequest(request) returns an empty list.



              Note the FilenameUtils#getName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.



              Alternatively you can also wrap this all in a Filter which parses it all automagically and put the stuff back in the parametermap of the request so that you can continue using request.getParameter() the usual way and retrieve the uploaded file by request.getAttribute(). You can find an example in this blog article.



              Workaround for GlassFish3 bug of getParameter() still returning null



              Note that Glassfish versions older than 3.1.2 had a bug wherein the getParameter() still returns null. If you are targeting such a container and can't upgrade it, then you need to extract the value from getPart() with help of this utility method:



              private static String getValue(Part part) throws IOException 
              BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
              StringBuilder value = new StringBuilder();
              char[] buffer = new char[1024];
              for (int length = 0; (length = reader.read(buffer)) > 0;)
              value.append(buffer, 0, length);

              return value.toString();





              String description = getValue(request.getPart("description")); // Retrieves <input type="text" name="description">


              Saving uploaded file (don't use getRealPath() nor part.write()!)



              Head to the following answers for detail on properly saving the obtained InputStream (the fileContent variable as shown in the above code snippets) to disk or database:



              • Recommended way to save uploaded files in a servlet application

              • How to upload an image and save it in database?

              • How to convert Part to Blob, so I can store it in MySQL?

              Serving uploaded file



              Head to the following answers for detail on properly serving the saved file from disk or database back to the client:



              • Load images from outside of webapps / webcontext / deploy folder using <h:graphicImage> or <img> tag

              • How to retrieve and display images from a database in a JSP page?

              • Simplest way to serve static data from outside the application server in a Java web application

              • Abstract template for static resource servlet supporting HTTP caching

              Ajaxifying the form



              Head to the following answers how to upload using Ajax (and jQuery). Do note that the servlet code to collect the form data does not need to be changed for this! Only the way how you respond may be changed, but this is rather trivial (i.e. instead of forwarding to JSP, just print some JSON or XML or even plain text depending on whatever the script responsible for the Ajax call is expecting).



              • How to upload files to server using JSP/Servlet and Ajax?

              • sending a file as multipart through xmlHttpRequest

              • HTML5 File Upload to Java Servlet


              Hope this all helps :)







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Aug 11 '17 at 18:09









              Joakim Erdfelt

              34.2k46198




              34.2k46198










              answered Mar 11 '10 at 12:27









              BalusCBalusC

              869k30932093259




              869k30932093259












              • Ah sorry, I was seeing request.getParts("file") and was confused x_x

                – Kagami Sascha Rosylight
                Nov 5 '16 at 22:02











              • With Servlet 3.0, if a MultipartConfig condition is violated (eg: maxFileSize), calling request.getParameter() returns null. Is this on purpose? What if I get some regular (text) parameters before calling getPart (and checking for an IllegalStateException)? This causes a NullPointerException to be thrown before I have a chance to check for the IllegalStateException.

                – theyuv
                Nov 20 '16 at 14:34












              • Please let me know if my question is unclear. Thanks.

                – theyuv
                Nov 20 '16 at 17:30











              • @BalusC I created a post related to this, do you have an idea how I could retrieve extra infos from File API webKitDirectory. More details here stackoverflow.com/questions/45419598/…

                – Rapster
                Jul 31 '17 at 23:52






              • 1





                Yeah, if someone tries to use the code in 3.0 section with tomcat 7, they might face issue in String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.part similar to me

                – raviraja
                Sep 24 '18 at 13:24


















              • Ah sorry, I was seeing request.getParts("file") and was confused x_x

                – Kagami Sascha Rosylight
                Nov 5 '16 at 22:02











              • With Servlet 3.0, if a MultipartConfig condition is violated (eg: maxFileSize), calling request.getParameter() returns null. Is this on purpose? What if I get some regular (text) parameters before calling getPart (and checking for an IllegalStateException)? This causes a NullPointerException to be thrown before I have a chance to check for the IllegalStateException.

                – theyuv
                Nov 20 '16 at 14:34












              • Please let me know if my question is unclear. Thanks.

                – theyuv
                Nov 20 '16 at 17:30











              • @BalusC I created a post related to this, do you have an idea how I could retrieve extra infos from File API webKitDirectory. More details here stackoverflow.com/questions/45419598/…

                – Rapster
                Jul 31 '17 at 23:52






              • 1





                Yeah, if someone tries to use the code in 3.0 section with tomcat 7, they might face issue in String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.part similar to me

                – raviraja
                Sep 24 '18 at 13:24

















              Ah sorry, I was seeing request.getParts("file") and was confused x_x

              – Kagami Sascha Rosylight
              Nov 5 '16 at 22:02





              Ah sorry, I was seeing request.getParts("file") and was confused x_x

              – Kagami Sascha Rosylight
              Nov 5 '16 at 22:02













              With Servlet 3.0, if a MultipartConfig condition is violated (eg: maxFileSize), calling request.getParameter() returns null. Is this on purpose? What if I get some regular (text) parameters before calling getPart (and checking for an IllegalStateException)? This causes a NullPointerException to be thrown before I have a chance to check for the IllegalStateException.

              – theyuv
              Nov 20 '16 at 14:34






              With Servlet 3.0, if a MultipartConfig condition is violated (eg: maxFileSize), calling request.getParameter() returns null. Is this on purpose? What if I get some regular (text) parameters before calling getPart (and checking for an IllegalStateException)? This causes a NullPointerException to be thrown before I have a chance to check for the IllegalStateException.

              – theyuv
              Nov 20 '16 at 14:34














              Please let me know if my question is unclear. Thanks.

              – theyuv
              Nov 20 '16 at 17:30





              Please let me know if my question is unclear. Thanks.

              – theyuv
              Nov 20 '16 at 17:30













              @BalusC I created a post related to this, do you have an idea how I could retrieve extra infos from File API webKitDirectory. More details here stackoverflow.com/questions/45419598/…

              – Rapster
              Jul 31 '17 at 23:52





              @BalusC I created a post related to this, do you have an idea how I could retrieve extra infos from File API webKitDirectory. More details here stackoverflow.com/questions/45419598/…

              – Rapster
              Jul 31 '17 at 23:52




              1




              1





              Yeah, if someone tries to use the code in 3.0 section with tomcat 7, they might face issue in String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.part similar to me

              – raviraja
              Sep 24 '18 at 13:24






              Yeah, if someone tries to use the code in 3.0 section with tomcat 7, they might face issue in String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.part similar to me

              – raviraja
              Sep 24 '18 at 13:24














              25














              If you happen to use Spring MVC, this is how to:
              (I'm leaving this here in case someone find it useful).



              Use a form with enctype attribute set to "multipart/form-data" (Same as BalusC's Answer)



              <form action="upload" method="post" enctype="multipart/form-data">
              <input type="file" name="file" />
              <input type="submit" value="Upload"/>
              </form>


              In your controller, map the request parameter file to MultipartFile type as follows:



              @RequestMapping(value = "/upload", method = RequestMethod.POST)
              public void handleUpload(@RequestParam("file") MultipartFile file) throws IOException
              if (!file.isEmpty())
              byte[] bytes = file.getBytes(); // alternatively, file.getInputStream();
              // application logic




              You can get the filename and size using MultipartFile's getOriginalFilename() and getSize().



              I've tested this with Spring version 4.1.1.RELEASE.






              share|improve this answer























              • If I'm not mistaken, this requires that you configure a bean in your server's application config...

                – Kenny Worden
                Jul 19 '18 at 21:36















              25














              If you happen to use Spring MVC, this is how to:
              (I'm leaving this here in case someone find it useful).



              Use a form with enctype attribute set to "multipart/form-data" (Same as BalusC's Answer)



              <form action="upload" method="post" enctype="multipart/form-data">
              <input type="file" name="file" />
              <input type="submit" value="Upload"/>
              </form>


              In your controller, map the request parameter file to MultipartFile type as follows:



              @RequestMapping(value = "/upload", method = RequestMethod.POST)
              public void handleUpload(@RequestParam("file") MultipartFile file) throws IOException
              if (!file.isEmpty())
              byte[] bytes = file.getBytes(); // alternatively, file.getInputStream();
              // application logic




              You can get the filename and size using MultipartFile's getOriginalFilename() and getSize().



              I've tested this with Spring version 4.1.1.RELEASE.






              share|improve this answer























              • If I'm not mistaken, this requires that you configure a bean in your server's application config...

                – Kenny Worden
                Jul 19 '18 at 21:36













              25












              25








              25







              If you happen to use Spring MVC, this is how to:
              (I'm leaving this here in case someone find it useful).



              Use a form with enctype attribute set to "multipart/form-data" (Same as BalusC's Answer)



              <form action="upload" method="post" enctype="multipart/form-data">
              <input type="file" name="file" />
              <input type="submit" value="Upload"/>
              </form>


              In your controller, map the request parameter file to MultipartFile type as follows:



              @RequestMapping(value = "/upload", method = RequestMethod.POST)
              public void handleUpload(@RequestParam("file") MultipartFile file) throws IOException
              if (!file.isEmpty())
              byte[] bytes = file.getBytes(); // alternatively, file.getInputStream();
              // application logic




              You can get the filename and size using MultipartFile's getOriginalFilename() and getSize().



              I've tested this with Spring version 4.1.1.RELEASE.






              share|improve this answer













              If you happen to use Spring MVC, this is how to:
              (I'm leaving this here in case someone find it useful).



              Use a form with enctype attribute set to "multipart/form-data" (Same as BalusC's Answer)



              <form action="upload" method="post" enctype="multipart/form-data">
              <input type="file" name="file" />
              <input type="submit" value="Upload"/>
              </form>


              In your controller, map the request parameter file to MultipartFile type as follows:



              @RequestMapping(value = "/upload", method = RequestMethod.POST)
              public void handleUpload(@RequestParam("file") MultipartFile file) throws IOException
              if (!file.isEmpty())
              byte[] bytes = file.getBytes(); // alternatively, file.getInputStream();
              // application logic




              You can get the filename and size using MultipartFile's getOriginalFilename() and getSize().



              I've tested this with Spring version 4.1.1.RELEASE.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Aug 26 '15 at 12:39









              AmilaAmila

              4,59512144




              4,59512144












              • If I'm not mistaken, this requires that you configure a bean in your server's application config...

                – Kenny Worden
                Jul 19 '18 at 21:36

















              • If I'm not mistaken, this requires that you configure a bean in your server's application config...

                – Kenny Worden
                Jul 19 '18 at 21:36
















              If I'm not mistaken, this requires that you configure a bean in your server's application config...

              – Kenny Worden
              Jul 19 '18 at 21:36





              If I'm not mistaken, this requires that you configure a bean in your server's application config...

              – Kenny Worden
              Jul 19 '18 at 21:36











              12














              You need the common-io.1.4.jar file to be included in your lib directory, or if you're working in any editor, like NetBeans, then you need to go to project properties and just add the JAR file and you will be done.



              To get the common.io.jar file just google it or just go to the Apache Tomcat website where you get the option for a free download of this file. But remember one thing: download the binary ZIP file if you're a Windows user.






              share|improve this answer

























              • Can't find .jar but .zip. Do you mean .zip?

                – Malwinder Singh
                Oct 9 '14 at 11:42















              12














              You need the common-io.1.4.jar file to be included in your lib directory, or if you're working in any editor, like NetBeans, then you need to go to project properties and just add the JAR file and you will be done.



              To get the common.io.jar file just google it or just go to the Apache Tomcat website where you get the option for a free download of this file. But remember one thing: download the binary ZIP file if you're a Windows user.






              share|improve this answer

























              • Can't find .jar but .zip. Do you mean .zip?

                – Malwinder Singh
                Oct 9 '14 at 11:42













              12












              12








              12







              You need the common-io.1.4.jar file to be included in your lib directory, or if you're working in any editor, like NetBeans, then you need to go to project properties and just add the JAR file and you will be done.



              To get the common.io.jar file just google it or just go to the Apache Tomcat website where you get the option for a free download of this file. But remember one thing: download the binary ZIP file if you're a Windows user.






              share|improve this answer















              You need the common-io.1.4.jar file to be included in your lib directory, or if you're working in any editor, like NetBeans, then you need to go to project properties and just add the JAR file and you will be done.



              To get the common.io.jar file just google it or just go to the Apache Tomcat website where you get the option for a free download of this file. But remember one thing: download the binary ZIP file if you're a Windows user.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 3 '12 at 12:25









              Peter Mortensen

              14.1k1988114




              14.1k1988114










              answered May 17 '12 at 11:11









              PranavPranav

              21637




              21637












              • Can't find .jar but .zip. Do you mean .zip?

                – Malwinder Singh
                Oct 9 '14 at 11:42

















              • Can't find .jar but .zip. Do you mean .zip?

                – Malwinder Singh
                Oct 9 '14 at 11:42
















              Can't find .jar but .zip. Do you mean .zip?

              – Malwinder Singh
              Oct 9 '14 at 11:42





              Can't find .jar but .zip. Do you mean .zip?

              – Malwinder Singh
              Oct 9 '14 at 11:42











              9














              I am Using common Servlet for every Html Form whether it has attachments or not.
              This Servlet returns a TreeMap where the keys are jsp name Parameters and values are User Inputs and saves all attachments in fixed directory and later you rename the directory of your choice.Here Connections is our custom interface having connection object. I think this will help you



              public class ServletCommonfunctions extends HttpServlet implements
              Connections

              private static final long serialVersionUID = 1L;

              public ServletCommonfunctions()

              protected void doPost(HttpServletRequest request,
              HttpServletResponse response) throws ServletException,
              IOException

              public SortedMap<String, String> savefilesindirectory(
              HttpServletRequest request, HttpServletResponse response)
              throws IOException
              // Map<String, String> key_values = Collections.synchronizedMap( new
              // TreeMap<String, String>());
              SortedMap<String, String> key_values = new TreeMap<String, String>();
              String dist = null, fact = null;
              PrintWriter out = response.getWriter();
              File file;
              String filePath = "E:\FSPATH1\2KL06CS048\";
              System.out.println("Directory Created ????????????"
              + new File(filePath).mkdir());
              int maxFileSize = 5000 * 1024;
              int maxMemSize = 5000 * 1024;
              // Verify the content type
              String contentType = request.getContentType();
              if ((contentType.indexOf("multipart/form-data") >= 0))
              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(filePath));
              // 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.
              @SuppressWarnings("unchecked")
              List<FileItem> fileItems = upload.parseRequest(request);
              // Process the uploaded file items
              Iterator<FileItem> i = fileItems.iterator();
              while (i.hasNext())
              FileItem fi = (FileItem) i.next();
              if (!fi.isFormField())
              // Get the uploaded file parameters
              String fileName = fi.getName();
              // 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);
              else
              key_values.put(fi.getFieldName(), fi.getString());


              catch (Exception ex)
              System.out.println(ex);


              return key_values;







              share|improve this answer

























              • @buhake sindi hey what should be the filepath if i m using live server or i live my project by uploading files to the server

                – AmanS
                Oct 20 '13 at 4:00






              • 2





                Any directory in live server.if you write a code to create a directory in servlet then directory will be created in live srver

                – feel good and programming
                Oct 20 '13 at 9:27















              9














              I am Using common Servlet for every Html Form whether it has attachments or not.
              This Servlet returns a TreeMap where the keys are jsp name Parameters and values are User Inputs and saves all attachments in fixed directory and later you rename the directory of your choice.Here Connections is our custom interface having connection object. I think this will help you



              public class ServletCommonfunctions extends HttpServlet implements
              Connections

              private static final long serialVersionUID = 1L;

              public ServletCommonfunctions()

              protected void doPost(HttpServletRequest request,
              HttpServletResponse response) throws ServletException,
              IOException

              public SortedMap<String, String> savefilesindirectory(
              HttpServletRequest request, HttpServletResponse response)
              throws IOException
              // Map<String, String> key_values = Collections.synchronizedMap( new
              // TreeMap<String, String>());
              SortedMap<String, String> key_values = new TreeMap<String, String>();
              String dist = null, fact = null;
              PrintWriter out = response.getWriter();
              File file;
              String filePath = "E:\FSPATH1\2KL06CS048\";
              System.out.println("Directory Created ????????????"
              + new File(filePath).mkdir());
              int maxFileSize = 5000 * 1024;
              int maxMemSize = 5000 * 1024;
              // Verify the content type
              String contentType = request.getContentType();
              if ((contentType.indexOf("multipart/form-data") >= 0))
              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(filePath));
              // 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.
              @SuppressWarnings("unchecked")
              List<FileItem> fileItems = upload.parseRequest(request);
              // Process the uploaded file items
              Iterator<FileItem> i = fileItems.iterator();
              while (i.hasNext())
              FileItem fi = (FileItem) i.next();
              if (!fi.isFormField())
              // Get the uploaded file parameters
              String fileName = fi.getName();
              // 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);
              else
              key_values.put(fi.getFieldName(), fi.getString());


              catch (Exception ex)
              System.out.println(ex);


              return key_values;







              share|improve this answer

























              • @buhake sindi hey what should be the filepath if i m using live server or i live my project by uploading files to the server

                – AmanS
                Oct 20 '13 at 4:00






              • 2





                Any directory in live server.if you write a code to create a directory in servlet then directory will be created in live srver

                – feel good and programming
                Oct 20 '13 at 9:27













              9












              9








              9







              I am Using common Servlet for every Html Form whether it has attachments or not.
              This Servlet returns a TreeMap where the keys are jsp name Parameters and values are User Inputs and saves all attachments in fixed directory and later you rename the directory of your choice.Here Connections is our custom interface having connection object. I think this will help you



              public class ServletCommonfunctions extends HttpServlet implements
              Connections

              private static final long serialVersionUID = 1L;

              public ServletCommonfunctions()

              protected void doPost(HttpServletRequest request,
              HttpServletResponse response) throws ServletException,
              IOException

              public SortedMap<String, String> savefilesindirectory(
              HttpServletRequest request, HttpServletResponse response)
              throws IOException
              // Map<String, String> key_values = Collections.synchronizedMap( new
              // TreeMap<String, String>());
              SortedMap<String, String> key_values = new TreeMap<String, String>();
              String dist = null, fact = null;
              PrintWriter out = response.getWriter();
              File file;
              String filePath = "E:\FSPATH1\2KL06CS048\";
              System.out.println("Directory Created ????????????"
              + new File(filePath).mkdir());
              int maxFileSize = 5000 * 1024;
              int maxMemSize = 5000 * 1024;
              // Verify the content type
              String contentType = request.getContentType();
              if ((contentType.indexOf("multipart/form-data") >= 0))
              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(filePath));
              // 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.
              @SuppressWarnings("unchecked")
              List<FileItem> fileItems = upload.parseRequest(request);
              // Process the uploaded file items
              Iterator<FileItem> i = fileItems.iterator();
              while (i.hasNext())
              FileItem fi = (FileItem) i.next();
              if (!fi.isFormField())
              // Get the uploaded file parameters
              String fileName = fi.getName();
              // 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);
              else
              key_values.put(fi.getFieldName(), fi.getString());


              catch (Exception ex)
              System.out.println(ex);


              return key_values;







              share|improve this answer















              I am Using common Servlet for every Html Form whether it has attachments or not.
              This Servlet returns a TreeMap where the keys are jsp name Parameters and values are User Inputs and saves all attachments in fixed directory and later you rename the directory of your choice.Here Connections is our custom interface having connection object. I think this will help you



              public class ServletCommonfunctions extends HttpServlet implements
              Connections

              private static final long serialVersionUID = 1L;

              public ServletCommonfunctions()

              protected void doPost(HttpServletRequest request,
              HttpServletResponse response) throws ServletException,
              IOException

              public SortedMap<String, String> savefilesindirectory(
              HttpServletRequest request, HttpServletResponse response)
              throws IOException
              // Map<String, String> key_values = Collections.synchronizedMap( new
              // TreeMap<String, String>());
              SortedMap<String, String> key_values = new TreeMap<String, String>();
              String dist = null, fact = null;
              PrintWriter out = response.getWriter();
              File file;
              String filePath = "E:\FSPATH1\2KL06CS048\";
              System.out.println("Directory Created ????????????"
              + new File(filePath).mkdir());
              int maxFileSize = 5000 * 1024;
              int maxMemSize = 5000 * 1024;
              // Verify the content type
              String contentType = request.getContentType();
              if ((contentType.indexOf("multipart/form-data") >= 0))
              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(filePath));
              // 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.
              @SuppressWarnings("unchecked")
              List<FileItem> fileItems = upload.parseRequest(request);
              // Process the uploaded file items
              Iterator<FileItem> i = fileItems.iterator();
              while (i.hasNext())
              FileItem fi = (FileItem) i.next();
              if (!fi.isFormField())
              // Get the uploaded file parameters
              String fileName = fi.getName();
              // 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);
              else
              key_values.put(fi.getFieldName(), fi.getString());


              catch (Exception ex)
              System.out.println(ex);


              return key_values;








              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jul 9 '13 at 22:39









              Buhake Sindi

              72.5k24146206




              72.5k24146206










              answered Jan 8 '13 at 5:50









              feel good and programmingfeel good and programming

              64821024




              64821024












              • @buhake sindi hey what should be the filepath if i m using live server or i live my project by uploading files to the server

                – AmanS
                Oct 20 '13 at 4:00






              • 2





                Any directory in live server.if you write a code to create a directory in servlet then directory will be created in live srver

                – feel good and programming
                Oct 20 '13 at 9:27

















              • @buhake sindi hey what should be the filepath if i m using live server or i live my project by uploading files to the server

                – AmanS
                Oct 20 '13 at 4:00






              • 2





                Any directory in live server.if you write a code to create a directory in servlet then directory will be created in live srver

                – feel good and programming
                Oct 20 '13 at 9:27
















              @buhake sindi hey what should be the filepath if i m using live server or i live my project by uploading files to the server

              – AmanS
              Oct 20 '13 at 4:00





              @buhake sindi hey what should be the filepath if i m using live server or i live my project by uploading files to the server

              – AmanS
              Oct 20 '13 at 4:00




              2




              2





              Any directory in live server.if you write a code to create a directory in servlet then directory will be created in live srver

              – feel good and programming
              Oct 20 '13 at 9:27





              Any directory in live server.if you write a code to create a directory in servlet then directory will be created in live srver

              – feel good and programming
              Oct 20 '13 at 9:27











              8














              Without component or external Library in Tomcat 6 o 7



              Enabling Upload in the web.xml file:



              http://joseluisbz.wordpress.com/2014/01/17/manually-installing-php-tomcat-and-httpd-lounge/#Enabling%20File%20Uploads.



              <servlet>
              <servlet-name>jsp</servlet-name>
              <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
              <multipart-config>
              <max-file-size>3145728</max-file-size>
              <max-request-size>5242880</max-request-size>
              </multipart-config>
              <init-param>
              <param-name>fork</param-name>
              <param-value>false</param-value>
              </init-param>
              <init-param>
              <param-name>xpoweredBy</param-name>
              <param-value>false</param-value>
              </init-param>
              <load-on-startup>3</load-on-startup>
              </servlet>


              AS YOU CAN SEE:



               <multipart-config>
              <max-file-size>3145728</max-file-size>
              <max-request-size>5242880</max-request-size>
              </multipart-config>


              Uploading Files using JSP. Files:



              In the html file



              <form method="post" enctype="multipart/form-data" name="Form" >

              <input type="file" name="fFoto" id="fFoto" value="" /></td>
              <input type="file" name="fResumen" id="fResumen" value=""/>


              In the JSP File or Servlet



               InputStream isFoto = request.getPart("fFoto").getInputStream();
              InputStream isResu = request.getPart("fResumen").getInputStream();
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              byte buf[] = new byte[8192];
              int qt = 0;
              while ((qt = isResu.read(buf)) != -1)
              baos.write(buf, 0, qt);

              String sResumen = baos.toString();


              Edit your code to servlet requirements, like max-file-size, max-request-size and other options that you can to set...






              share|improve this answer



























                8














                Without component or external Library in Tomcat 6 o 7



                Enabling Upload in the web.xml file:



                http://joseluisbz.wordpress.com/2014/01/17/manually-installing-php-tomcat-and-httpd-lounge/#Enabling%20File%20Uploads.



                <servlet>
                <servlet-name>jsp</servlet-name>
                <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
                <multipart-config>
                <max-file-size>3145728</max-file-size>
                <max-request-size>5242880</max-request-size>
                </multipart-config>
                <init-param>
                <param-name>fork</param-name>
                <param-value>false</param-value>
                </init-param>
                <init-param>
                <param-name>xpoweredBy</param-name>
                <param-value>false</param-value>
                </init-param>
                <load-on-startup>3</load-on-startup>
                </servlet>


                AS YOU CAN SEE:



                 <multipart-config>
                <max-file-size>3145728</max-file-size>
                <max-request-size>5242880</max-request-size>
                </multipart-config>


                Uploading Files using JSP. Files:



                In the html file



                <form method="post" enctype="multipart/form-data" name="Form" >

                <input type="file" name="fFoto" id="fFoto" value="" /></td>
                <input type="file" name="fResumen" id="fResumen" value=""/>


                In the JSP File or Servlet



                 InputStream isFoto = request.getPart("fFoto").getInputStream();
                InputStream isResu = request.getPart("fResumen").getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte buf[] = new byte[8192];
                int qt = 0;
                while ((qt = isResu.read(buf)) != -1)
                baos.write(buf, 0, qt);

                String sResumen = baos.toString();


                Edit your code to servlet requirements, like max-file-size, max-request-size and other options that you can to set...






                share|improve this answer

























                  8












                  8








                  8







                  Without component or external Library in Tomcat 6 o 7



                  Enabling Upload in the web.xml file:



                  http://joseluisbz.wordpress.com/2014/01/17/manually-installing-php-tomcat-and-httpd-lounge/#Enabling%20File%20Uploads.



                  <servlet>
                  <servlet-name>jsp</servlet-name>
                  <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
                  <multipart-config>
                  <max-file-size>3145728</max-file-size>
                  <max-request-size>5242880</max-request-size>
                  </multipart-config>
                  <init-param>
                  <param-name>fork</param-name>
                  <param-value>false</param-value>
                  </init-param>
                  <init-param>
                  <param-name>xpoweredBy</param-name>
                  <param-value>false</param-value>
                  </init-param>
                  <load-on-startup>3</load-on-startup>
                  </servlet>


                  AS YOU CAN SEE:



                   <multipart-config>
                  <max-file-size>3145728</max-file-size>
                  <max-request-size>5242880</max-request-size>
                  </multipart-config>


                  Uploading Files using JSP. Files:



                  In the html file



                  <form method="post" enctype="multipart/form-data" name="Form" >

                  <input type="file" name="fFoto" id="fFoto" value="" /></td>
                  <input type="file" name="fResumen" id="fResumen" value=""/>


                  In the JSP File or Servlet



                   InputStream isFoto = request.getPart("fFoto").getInputStream();
                  InputStream isResu = request.getPart("fResumen").getInputStream();
                  ByteArrayOutputStream baos = new ByteArrayOutputStream();
                  byte buf[] = new byte[8192];
                  int qt = 0;
                  while ((qt = isResu.read(buf)) != -1)
                  baos.write(buf, 0, qt);

                  String sResumen = baos.toString();


                  Edit your code to servlet requirements, like max-file-size, max-request-size and other options that you can to set...






                  share|improve this answer













                  Without component or external Library in Tomcat 6 o 7



                  Enabling Upload in the web.xml file:



                  http://joseluisbz.wordpress.com/2014/01/17/manually-installing-php-tomcat-and-httpd-lounge/#Enabling%20File%20Uploads.



                  <servlet>
                  <servlet-name>jsp</servlet-name>
                  <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
                  <multipart-config>
                  <max-file-size>3145728</max-file-size>
                  <max-request-size>5242880</max-request-size>
                  </multipart-config>
                  <init-param>
                  <param-name>fork</param-name>
                  <param-value>false</param-value>
                  </init-param>
                  <init-param>
                  <param-name>xpoweredBy</param-name>
                  <param-value>false</param-value>
                  </init-param>
                  <load-on-startup>3</load-on-startup>
                  </servlet>


                  AS YOU CAN SEE:



                   <multipart-config>
                  <max-file-size>3145728</max-file-size>
                  <max-request-size>5242880</max-request-size>
                  </multipart-config>


                  Uploading Files using JSP. Files:



                  In the html file



                  <form method="post" enctype="multipart/form-data" name="Form" >

                  <input type="file" name="fFoto" id="fFoto" value="" /></td>
                  <input type="file" name="fResumen" id="fResumen" value=""/>


                  In the JSP File or Servlet



                   InputStream isFoto = request.getPart("fFoto").getInputStream();
                  InputStream isResu = request.getPart("fResumen").getInputStream();
                  ByteArrayOutputStream baos = new ByteArrayOutputStream();
                  byte buf[] = new byte[8192];
                  int qt = 0;
                  while ((qt = isResu.read(buf)) != -1)
                  baos.write(buf, 0, qt);

                  String sResumen = baos.toString();


                  Edit your code to servlet requirements, like max-file-size, max-request-size and other options that you can to set...







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 25 '14 at 5:44









                  chepe luchochepe lucho

                  1,67812032




                  1,67812032





















                      8














                      For Spring MVC
                      I have been trying for hours to do this
                      and managed to have a simpler version that worked for taking form input both data and image.



                      <form action="/handleform" method="post" enctype="multipart/form-data">
                      <input type="text" name="name" />
                      <input type="text" name="age" />
                      <input type="file" name="file" />
                      <input type="submit" />
                      </form>


                      Controller to handle



                      @Controller
                      public class FormController
                      @RequestMapping(value="/handleform",method= RequestMethod.POST)
                      ModelAndView register(@RequestParam String name, @RequestParam int age, @RequestParam MultipartFile file)
                      throws ServletException, IOException

                      System.out.println(name);
                      System.out.println(age);
                      if(!file.isEmpty())
                      byte[] bytes = file.getBytes();
                      String filename = file.getOriginalFilename();
                      BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("D:/" + filename)));
                      stream.write(bytes);
                      stream.flush();
                      stream.close();

                      return new ModelAndView("index");




                      Hope it helps :)






                      share|improve this answer























                      • Can you please share select image form db mysql and show it on jsp/html?

                        – Ved Prakash
                        Mar 13 at 12:27















                      8














                      For Spring MVC
                      I have been trying for hours to do this
                      and managed to have a simpler version that worked for taking form input both data and image.



                      <form action="/handleform" method="post" enctype="multipart/form-data">
                      <input type="text" name="name" />
                      <input type="text" name="age" />
                      <input type="file" name="file" />
                      <input type="submit" />
                      </form>


                      Controller to handle



                      @Controller
                      public class FormController
                      @RequestMapping(value="/handleform",method= RequestMethod.POST)
                      ModelAndView register(@RequestParam String name, @RequestParam int age, @RequestParam MultipartFile file)
                      throws ServletException, IOException

                      System.out.println(name);
                      System.out.println(age);
                      if(!file.isEmpty())
                      byte[] bytes = file.getBytes();
                      String filename = file.getOriginalFilename();
                      BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("D:/" + filename)));
                      stream.write(bytes);
                      stream.flush();
                      stream.close();

                      return new ModelAndView("index");




                      Hope it helps :)






                      share|improve this answer























                      • Can you please share select image form db mysql and show it on jsp/html?

                        – Ved Prakash
                        Mar 13 at 12:27













                      8












                      8








                      8







                      For Spring MVC
                      I have been trying for hours to do this
                      and managed to have a simpler version that worked for taking form input both data and image.



                      <form action="/handleform" method="post" enctype="multipart/form-data">
                      <input type="text" name="name" />
                      <input type="text" name="age" />
                      <input type="file" name="file" />
                      <input type="submit" />
                      </form>


                      Controller to handle



                      @Controller
                      public class FormController
                      @RequestMapping(value="/handleform",method= RequestMethod.POST)
                      ModelAndView register(@RequestParam String name, @RequestParam int age, @RequestParam MultipartFile file)
                      throws ServletException, IOException

                      System.out.println(name);
                      System.out.println(age);
                      if(!file.isEmpty())
                      byte[] bytes = file.getBytes();
                      String filename = file.getOriginalFilename();
                      BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("D:/" + filename)));
                      stream.write(bytes);
                      stream.flush();
                      stream.close();

                      return new ModelAndView("index");




                      Hope it helps :)






                      share|improve this answer













                      For Spring MVC
                      I have been trying for hours to do this
                      and managed to have a simpler version that worked for taking form input both data and image.



                      <form action="/handleform" method="post" enctype="multipart/form-data">
                      <input type="text" name="name" />
                      <input type="text" name="age" />
                      <input type="file" name="file" />
                      <input type="submit" />
                      </form>


                      Controller to handle



                      @Controller
                      public class FormController
                      @RequestMapping(value="/handleform",method= RequestMethod.POST)
                      ModelAndView register(@RequestParam String name, @RequestParam int age, @RequestParam MultipartFile file)
                      throws ServletException, IOException

                      System.out.println(name);
                      System.out.println(age);
                      if(!file.isEmpty())
                      byte[] bytes = file.getBytes();
                      String filename = file.getOriginalFilename();
                      BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("D:/" + filename)));
                      stream.write(bytes);
                      stream.flush();
                      stream.close();

                      return new ModelAndView("index");




                      Hope it helps :)







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jul 15 '17 at 19:42









                      Shivangi GuptaShivangi Gupta

                      438511




                      438511












                      • Can you please share select image form db mysql and show it on jsp/html?

                        – Ved Prakash
                        Mar 13 at 12:27

















                      • Can you please share select image form db mysql and show it on jsp/html?

                        – Ved Prakash
                        Mar 13 at 12:27
















                      Can you please share select image form db mysql and show it on jsp/html?

                      – Ved Prakash
                      Mar 13 at 12:27





                      Can you please share select image form db mysql and show it on jsp/html?

                      – Ved Prakash
                      Mar 13 at 12:27











                      6














                      Another source of this problem occurs if you are using Geronimo with its embedded Tomcat. In this case, after many iterations of testing commons-io and commons-fileupload, the problem arises from a parent classloader handling the commons-xxx jars. This has to be prevented. The crash always occurred at:



                      fileItems = uploader.parseRequest(request);


                      Note that the List type of fileItems has changed with the current version of commons-fileupload to be specifically List<FileItem> as opposed to prior versions where it was generic List.



                      I added the source code for commons-fileupload and commons-io into my Eclipse project to trace the actual error and finally got some insight. First, the exception thrown is of type Throwable not the stated FileIOException nor even Exception (these will not be trapped). Second, the error message is obfuscatory in that it stated class not found because axis2 could not find commons-io. Axis2 is not used in my project at all but exists as a folder in the Geronimo repository subdirectory as part of standard installation.



                      Finally, I found 1 place that posed a working solution which successfully solved my problem. You must hide the jars from parent loader in the deployment plan. This was put into geronimo-web.xml with my full file shown below.



                      Pasted from <http://osdir.com/ml/user-geronimo-apache/2011-03/msg00026.html> 



                      <?xml version="1.0" encoding="UTF-8" standalone="no"?>
                      <web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:pers="http://java.sun.com/xml/ns/persistence" xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1">
                      <dep:environment>
                      <dep:moduleId>
                      <dep:groupId>DataStar</dep:groupId>
                      <dep:artifactId>DataStar</dep:artifactId>
                      <dep:version>1.0</dep:version>
                      <dep:type>car</dep:type>
                      </dep:moduleId>

                      <!--Don't load commons-io or fileupload from parent classloaders-->
                      <dep:hidden-classes>
                      <dep:filter>org.apache.commons.io</dep:filter>
                      <dep:filter>org.apache.commons.fileupload</dep:filter>
                      </dep:hidden-classes>
                      <dep:inverse-classloading/>


                      </dep:environment>
                      <web:context-root>/DataStar</web:context-root>
                      </web:web-app>





                      share|improve this answer



























                        6














                        Another source of this problem occurs if you are using Geronimo with its embedded Tomcat. In this case, after many iterations of testing commons-io and commons-fileupload, the problem arises from a parent classloader handling the commons-xxx jars. This has to be prevented. The crash always occurred at:



                        fileItems = uploader.parseRequest(request);


                        Note that the List type of fileItems has changed with the current version of commons-fileupload to be specifically List<FileItem> as opposed to prior versions where it was generic List.



                        I added the source code for commons-fileupload and commons-io into my Eclipse project to trace the actual error and finally got some insight. First, the exception thrown is of type Throwable not the stated FileIOException nor even Exception (these will not be trapped). Second, the error message is obfuscatory in that it stated class not found because axis2 could not find commons-io. Axis2 is not used in my project at all but exists as a folder in the Geronimo repository subdirectory as part of standard installation.



                        Finally, I found 1 place that posed a working solution which successfully solved my problem. You must hide the jars from parent loader in the deployment plan. This was put into geronimo-web.xml with my full file shown below.



                        Pasted from <http://osdir.com/ml/user-geronimo-apache/2011-03/msg00026.html> 



                        <?xml version="1.0" encoding="UTF-8" standalone="no"?>
                        <web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:pers="http://java.sun.com/xml/ns/persistence" xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1">
                        <dep:environment>
                        <dep:moduleId>
                        <dep:groupId>DataStar</dep:groupId>
                        <dep:artifactId>DataStar</dep:artifactId>
                        <dep:version>1.0</dep:version>
                        <dep:type>car</dep:type>
                        </dep:moduleId>

                        <!--Don't load commons-io or fileupload from parent classloaders-->
                        <dep:hidden-classes>
                        <dep:filter>org.apache.commons.io</dep:filter>
                        <dep:filter>org.apache.commons.fileupload</dep:filter>
                        </dep:hidden-classes>
                        <dep:inverse-classloading/>


                        </dep:environment>
                        <web:context-root>/DataStar</web:context-root>
                        </web:web-app>





                        share|improve this answer

























                          6












                          6








                          6







                          Another source of this problem occurs if you are using Geronimo with its embedded Tomcat. In this case, after many iterations of testing commons-io and commons-fileupload, the problem arises from a parent classloader handling the commons-xxx jars. This has to be prevented. The crash always occurred at:



                          fileItems = uploader.parseRequest(request);


                          Note that the List type of fileItems has changed with the current version of commons-fileupload to be specifically List<FileItem> as opposed to prior versions where it was generic List.



                          I added the source code for commons-fileupload and commons-io into my Eclipse project to trace the actual error and finally got some insight. First, the exception thrown is of type Throwable not the stated FileIOException nor even Exception (these will not be trapped). Second, the error message is obfuscatory in that it stated class not found because axis2 could not find commons-io. Axis2 is not used in my project at all but exists as a folder in the Geronimo repository subdirectory as part of standard installation.



                          Finally, I found 1 place that posed a working solution which successfully solved my problem. You must hide the jars from parent loader in the deployment plan. This was put into geronimo-web.xml with my full file shown below.



                          Pasted from <http://osdir.com/ml/user-geronimo-apache/2011-03/msg00026.html> 



                          <?xml version="1.0" encoding="UTF-8" standalone="no"?>
                          <web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:pers="http://java.sun.com/xml/ns/persistence" xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1">
                          <dep:environment>
                          <dep:moduleId>
                          <dep:groupId>DataStar</dep:groupId>
                          <dep:artifactId>DataStar</dep:artifactId>
                          <dep:version>1.0</dep:version>
                          <dep:type>car</dep:type>
                          </dep:moduleId>

                          <!--Don't load commons-io or fileupload from parent classloaders-->
                          <dep:hidden-classes>
                          <dep:filter>org.apache.commons.io</dep:filter>
                          <dep:filter>org.apache.commons.fileupload</dep:filter>
                          </dep:hidden-classes>
                          <dep:inverse-classloading/>


                          </dep:environment>
                          <web:context-root>/DataStar</web:context-root>
                          </web:web-app>





                          share|improve this answer













                          Another source of this problem occurs if you are using Geronimo with its embedded Tomcat. In this case, after many iterations of testing commons-io and commons-fileupload, the problem arises from a parent classloader handling the commons-xxx jars. This has to be prevented. The crash always occurred at:



                          fileItems = uploader.parseRequest(request);


                          Note that the List type of fileItems has changed with the current version of commons-fileupload to be specifically List<FileItem> as opposed to prior versions where it was generic List.



                          I added the source code for commons-fileupload and commons-io into my Eclipse project to trace the actual error and finally got some insight. First, the exception thrown is of type Throwable not the stated FileIOException nor even Exception (these will not be trapped). Second, the error message is obfuscatory in that it stated class not found because axis2 could not find commons-io. Axis2 is not used in my project at all but exists as a folder in the Geronimo repository subdirectory as part of standard installation.



                          Finally, I found 1 place that posed a working solution which successfully solved my problem. You must hide the jars from parent loader in the deployment plan. This was put into geronimo-web.xml with my full file shown below.



                          Pasted from <http://osdir.com/ml/user-geronimo-apache/2011-03/msg00026.html> 



                          <?xml version="1.0" encoding="UTF-8" standalone="no"?>
                          <web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:pers="http://java.sun.com/xml/ns/persistence" xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1">
                          <dep:environment>
                          <dep:moduleId>
                          <dep:groupId>DataStar</dep:groupId>
                          <dep:artifactId>DataStar</dep:artifactId>
                          <dep:version>1.0</dep:version>
                          <dep:type>car</dep:type>
                          </dep:moduleId>

                          <!--Don't load commons-io or fileupload from parent classloaders-->
                          <dep:hidden-classes>
                          <dep:filter>org.apache.commons.io</dep:filter>
                          <dep:filter>org.apache.commons.fileupload</dep:filter>
                          </dep:hidden-classes>
                          <dep:inverse-classloading/>


                          </dep:environment>
                          <web:context-root>/DataStar</web:context-root>
                          </web:web-app>






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Sep 10 '13 at 15:15









                          Geoffrey MalafskyGeoffrey Malafsky

                          15425




                          15425





















                              0














                              Here's an example using apache commons-fileupload:



                              // apache commons-fileupload to handle file upload
                              DiskFileItemFactory factory = new DiskFileItemFactory();
                              factory.setRepository(new File(DataSources.TORRENTS_DIR()));
                              ServletFileUpload fileUpload = new ServletFileUpload(factory);

                              List<FileItem> items = fileUpload.parseRequest(req.raw());
                              FileItem item = items.stream()
                              .filter(e ->
                              "the_upload_name".equals(e.getFieldName()))
                              .findFirst().get();
                              String fileName = item.getName();

                              item.write(new File(dir, fileName));
                              log.info(fileName);





                              share|improve this answer



























                                0














                                Here's an example using apache commons-fileupload:



                                // apache commons-fileupload to handle file upload
                                DiskFileItemFactory factory = new DiskFileItemFactory();
                                factory.setRepository(new File(DataSources.TORRENTS_DIR()));
                                ServletFileUpload fileUpload = new ServletFileUpload(factory);

                                List<FileItem> items = fileUpload.parseRequest(req.raw());
                                FileItem item = items.stream()
                                .filter(e ->
                                "the_upload_name".equals(e.getFieldName()))
                                .findFirst().get();
                                String fileName = item.getName();

                                item.write(new File(dir, fileName));
                                log.info(fileName);





                                share|improve this answer

























                                  0












                                  0








                                  0







                                  Here's an example using apache commons-fileupload:



                                  // apache commons-fileupload to handle file upload
                                  DiskFileItemFactory factory = new DiskFileItemFactory();
                                  factory.setRepository(new File(DataSources.TORRENTS_DIR()));
                                  ServletFileUpload fileUpload = new ServletFileUpload(factory);

                                  List<FileItem> items = fileUpload.parseRequest(req.raw());
                                  FileItem item = items.stream()
                                  .filter(e ->
                                  "the_upload_name".equals(e.getFieldName()))
                                  .findFirst().get();
                                  String fileName = item.getName();

                                  item.write(new File(dir, fileName));
                                  log.info(fileName);





                                  share|improve this answer













                                  Here's an example using apache commons-fileupload:



                                  // apache commons-fileupload to handle file upload
                                  DiskFileItemFactory factory = new DiskFileItemFactory();
                                  factory.setRepository(new File(DataSources.TORRENTS_DIR()));
                                  ServletFileUpload fileUpload = new ServletFileUpload(factory);

                                  List<FileItem> items = fileUpload.parseRequest(req.raw());
                                  FileItem item = items.stream()
                                  .filter(e ->
                                  "the_upload_name".equals(e.getFieldName()))
                                  .findFirst().get();
                                  String fileName = item.getName();

                                  item.write(new File(dir, fileName));
                                  log.info(fileName);






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered May 21 '15 at 16:49









                                  thoulihathouliha

                                  3,05322332




                                  3,05322332





















                                      -1














                                      you can upload file using jsp /servlet.



                                      <form action="UploadFileServlet" method="post">
                                      <input type="text" name="description" />
                                      <input type="file" name="file" />
                                      <input type="submit" />
                                      </form>


                                      on the other hand server side.
                                      use following code.



                                       package com.abc..servlet;

                                      import java.io.File;
                                      ---------
                                      --------


                                      /**
                                      * Servlet implementation class UploadFileServlet
                                      */
                                      public class UploadFileServlet extends HttpServlet
                                      private static final long serialVersionUID = 1L;

                                      public UploadFileServlet()
                                      super();
                                      // TODO Auto-generated constructor stub

                                      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
                                      // TODO Auto-generated method stub
                                      response.sendRedirect("../jsp/ErrorPage.jsp");


                                      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
                                      // TODO Auto-generated method stub

                                      PrintWriter out = response.getWriter();
                                      HttpSession httpSession = request.getSession();
                                      String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;

                                      String path1 = filePathUpload;
                                      String filename = null;
                                      File path = null;
                                      FileItem item=null;


                                      boolean isMultipart = ServletFileUpload.isMultipartContent(request);

                                      if (isMultipart)
                                      FileItemFactory factory = new DiskFileItemFactory();
                                      ServletFileUpload upload = new ServletFileUpload(factory);
                                      String FieldName = "";
                                      try
                                      List items = upload.parseRequest(request);
                                      Iterator iterator = items.iterator();
                                      while (iterator.hasNext())
                                      item = (FileItem) iterator.next();

                                      if (fieldname.equals("description"))
                                      description = item.getString();


                                      if (!item.isFormField())
                                      filename = item.getName();
                                      path = new File(path1 + File.separator);
                                      if (!path.exists())
                                      boolean status = path.mkdirs();

                                      /* START OF CODE FRO PRIVILEDGE*/

                                      File uploadedFile = new File(path + Filename); // for copy file
                                      item.write(uploadedFile);

                                      else
                                      f1 = item.getName();


                                      // END OF WHILE
                                      response.sendRedirect("welcome.jsp");
                                      catch (FileUploadException e)
                                      e.printStackTrace();
                                      catch (Exception e)
                                      e.printStackTrace();


                                      }

                                      }





                                      share|improve this answer



























                                        -1














                                        you can upload file using jsp /servlet.



                                        <form action="UploadFileServlet" method="post">
                                        <input type="text" name="description" />
                                        <input type="file" name="file" />
                                        <input type="submit" />
                                        </form>


                                        on the other hand server side.
                                        use following code.



                                         package com.abc..servlet;

                                        import java.io.File;
                                        ---------
                                        --------


                                        /**
                                        * Servlet implementation class UploadFileServlet
                                        */
                                        public class UploadFileServlet extends HttpServlet
                                        private static final long serialVersionUID = 1L;

                                        public UploadFileServlet()
                                        super();
                                        // TODO Auto-generated constructor stub

                                        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
                                        // TODO Auto-generated method stub
                                        response.sendRedirect("../jsp/ErrorPage.jsp");


                                        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
                                        // TODO Auto-generated method stub

                                        PrintWriter out = response.getWriter();
                                        HttpSession httpSession = request.getSession();
                                        String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;

                                        String path1 = filePathUpload;
                                        String filename = null;
                                        File path = null;
                                        FileItem item=null;


                                        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

                                        if (isMultipart)
                                        FileItemFactory factory = new DiskFileItemFactory();
                                        ServletFileUpload upload = new ServletFileUpload(factory);
                                        String FieldName = "";
                                        try
                                        List items = upload.parseRequest(request);
                                        Iterator iterator = items.iterator();
                                        while (iterator.hasNext())
                                        item = (FileItem) iterator.next();

                                        if (fieldname.equals("description"))
                                        description = item.getString();


                                        if (!item.isFormField())
                                        filename = item.getName();
                                        path = new File(path1 + File.separator);
                                        if (!path.exists())
                                        boolean status = path.mkdirs();

                                        /* START OF CODE FRO PRIVILEDGE*/

                                        File uploadedFile = new File(path + Filename); // for copy file
                                        item.write(uploadedFile);

                                        else
                                        f1 = item.getName();


                                        // END OF WHILE
                                        response.sendRedirect("welcome.jsp");
                                        catch (FileUploadException e)
                                        e.printStackTrace();
                                        catch (Exception e)
                                        e.printStackTrace();


                                        }

                                        }





                                        share|improve this answer

























                                          -1












                                          -1








                                          -1







                                          you can upload file using jsp /servlet.



                                          <form action="UploadFileServlet" method="post">
                                          <input type="text" name="description" />
                                          <input type="file" name="file" />
                                          <input type="submit" />
                                          </form>


                                          on the other hand server side.
                                          use following code.



                                           package com.abc..servlet;

                                          import java.io.File;
                                          ---------
                                          --------


                                          /**
                                          * Servlet implementation class UploadFileServlet
                                          */
                                          public class UploadFileServlet extends HttpServlet
                                          private static final long serialVersionUID = 1L;

                                          public UploadFileServlet()
                                          super();
                                          // TODO Auto-generated constructor stub

                                          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
                                          // TODO Auto-generated method stub
                                          response.sendRedirect("../jsp/ErrorPage.jsp");


                                          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
                                          // TODO Auto-generated method stub

                                          PrintWriter out = response.getWriter();
                                          HttpSession httpSession = request.getSession();
                                          String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;

                                          String path1 = filePathUpload;
                                          String filename = null;
                                          File path = null;
                                          FileItem item=null;


                                          boolean isMultipart = ServletFileUpload.isMultipartContent(request);

                                          if (isMultipart)
                                          FileItemFactory factory = new DiskFileItemFactory();
                                          ServletFileUpload upload = new ServletFileUpload(factory);
                                          String FieldName = "";
                                          try
                                          List items = upload.parseRequest(request);
                                          Iterator iterator = items.iterator();
                                          while (iterator.hasNext())
                                          item = (FileItem) iterator.next();

                                          if (fieldname.equals("description"))
                                          description = item.getString();


                                          if (!item.isFormField())
                                          filename = item.getName();
                                          path = new File(path1 + File.separator);
                                          if (!path.exists())
                                          boolean status = path.mkdirs();

                                          /* START OF CODE FRO PRIVILEDGE*/

                                          File uploadedFile = new File(path + Filename); // for copy file
                                          item.write(uploadedFile);

                                          else
                                          f1 = item.getName();


                                          // END OF WHILE
                                          response.sendRedirect("welcome.jsp");
                                          catch (FileUploadException e)
                                          e.printStackTrace();
                                          catch (Exception e)
                                          e.printStackTrace();


                                          }

                                          }





                                          share|improve this answer













                                          you can upload file using jsp /servlet.



                                          <form action="UploadFileServlet" method="post">
                                          <input type="text" name="description" />
                                          <input type="file" name="file" />
                                          <input type="submit" />
                                          </form>


                                          on the other hand server side.
                                          use following code.



                                           package com.abc..servlet;

                                          import java.io.File;
                                          ---------
                                          --------


                                          /**
                                          * Servlet implementation class UploadFileServlet
                                          */
                                          public class UploadFileServlet extends HttpServlet
                                          private static final long serialVersionUID = 1L;

                                          public UploadFileServlet()
                                          super();
                                          // TODO Auto-generated constructor stub

                                          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
                                          // TODO Auto-generated method stub
                                          response.sendRedirect("../jsp/ErrorPage.jsp");


                                          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
                                          // TODO Auto-generated method stub

                                          PrintWriter out = response.getWriter();
                                          HttpSession httpSession = request.getSession();
                                          String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;

                                          String path1 = filePathUpload;
                                          String filename = null;
                                          File path = null;
                                          FileItem item=null;


                                          boolean isMultipart = ServletFileUpload.isMultipartContent(request);

                                          if (isMultipart)
                                          FileItemFactory factory = new DiskFileItemFactory();
                                          ServletFileUpload upload = new ServletFileUpload(factory);
                                          String FieldName = "";
                                          try
                                          List items = upload.parseRequest(request);
                                          Iterator iterator = items.iterator();
                                          while (iterator.hasNext())
                                          item = (FileItem) iterator.next();

                                          if (fieldname.equals("description"))
                                          description = item.getString();


                                          if (!item.isFormField())
                                          filename = item.getName();
                                          path = new File(path1 + File.separator);
                                          if (!path.exists())
                                          boolean status = path.mkdirs();

                                          /* START OF CODE FRO PRIVILEDGE*/

                                          File uploadedFile = new File(path + Filename); // for copy file
                                          item.write(uploadedFile);

                                          else
                                          f1 = item.getName();


                                          // END OF WHILE
                                          response.sendRedirect("welcome.jsp");
                                          catch (FileUploadException e)
                                          e.printStackTrace();
                                          catch (Exception e)
                                          e.printStackTrace();


                                          }

                                          }






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Feb 4 '14 at 10:00









                                          Mitul MaheshwariMitul Maheshwari

                                          2,04141637




                                          2,04141637





















                                              -1














                                              DiskFileUpload upload=new DiskFileUpload();


                                              From this object you have to get file items and fields then yo can store into server like followed:



                                              String loc="./webapps/prjct name/server folder/"+contentid+extension;
                                              File uploadFile=new File(loc);
                                              item.write(uploadFile);





                                              share|improve this answer





























                                                -1














                                                DiskFileUpload upload=new DiskFileUpload();


                                                From this object you have to get file items and fields then yo can store into server like followed:



                                                String loc="./webapps/prjct name/server folder/"+contentid+extension;
                                                File uploadFile=new File(loc);
                                                item.write(uploadFile);





                                                share|improve this answer



























                                                  -1












                                                  -1








                                                  -1







                                                  DiskFileUpload upload=new DiskFileUpload();


                                                  From this object you have to get file items and fields then yo can store into server like followed:



                                                  String loc="./webapps/prjct name/server folder/"+contentid+extension;
                                                  File uploadFile=new File(loc);
                                                  item.write(uploadFile);





                                                  share|improve this answer















                                                  DiskFileUpload upload=new DiskFileUpload();


                                                  From this object you have to get file items and fields then yo can store into server like followed:



                                                  String loc="./webapps/prjct name/server folder/"+contentid+extension;
                                                  File uploadFile=new File(loc);
                                                  item.write(uploadFile);






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Sep 7 '18 at 22:28









                                                  Pritam Banerjee

                                                  11.3k65071




                                                  11.3k65071










                                                  answered Mar 23 '15 at 12:37









                                                  Mahender Reddy YasaMahender Reddy Yasa

                                                  146617




                                                  146617





















                                                      -2














                                                      Sending multiple file for file we have to use enctype="multipart/form-data"

                                                      and to send multiple file use multiple="multiple" in input tag



                                                      <form action="upload" method="post" enctype="multipart/form-data">
                                                      <input type="file" name="fileattachments" multiple="multiple"/>
                                                      <input type="submit" />
                                                      </form>





                                                      share|improve this answer




















                                                      • 2





                                                        How would we go about doing getPart("fileattachments") so we get an array of Parts instead? I don't think getPart for multiple files will work?

                                                        – CyberMew
                                                        Sep 29 '15 at 6:38















                                                      -2














                                                      Sending multiple file for file we have to use enctype="multipart/form-data"

                                                      and to send multiple file use multiple="multiple" in input tag



                                                      <form action="upload" method="post" enctype="multipart/form-data">
                                                      <input type="file" name="fileattachments" multiple="multiple"/>
                                                      <input type="submit" />
                                                      </form>





                                                      share|improve this answer




















                                                      • 2





                                                        How would we go about doing getPart("fileattachments") so we get an array of Parts instead? I don't think getPart for multiple files will work?

                                                        – CyberMew
                                                        Sep 29 '15 at 6:38













                                                      -2












                                                      -2








                                                      -2







                                                      Sending multiple file for file we have to use enctype="multipart/form-data"

                                                      and to send multiple file use multiple="multiple" in input tag



                                                      <form action="upload" method="post" enctype="multipart/form-data">
                                                      <input type="file" name="fileattachments" multiple="multiple"/>
                                                      <input type="submit" />
                                                      </form>





                                                      share|improve this answer















                                                      Sending multiple file for file we have to use enctype="multipart/form-data"

                                                      and to send multiple file use multiple="multiple" in input tag



                                                      <form action="upload" method="post" enctype="multipart/form-data">
                                                      <input type="file" name="fileattachments" multiple="multiple"/>
                                                      <input type="submit" />
                                                      </form>






                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Jan 27 '14 at 4:33









                                                      Aniket Kulkarni

                                                      10.9k75771




                                                      10.9k75771










                                                      answered Oct 24 '13 at 9:35









                                                      rohan kamatrohan kamat

                                                      557512




                                                      557512







                                                      • 2





                                                        How would we go about doing getPart("fileattachments") so we get an array of Parts instead? I don't think getPart for multiple files will work?

                                                        – CyberMew
                                                        Sep 29 '15 at 6:38












                                                      • 2





                                                        How would we go about doing getPart("fileattachments") so we get an array of Parts instead? I don't think getPart for multiple files will work?

                                                        – CyberMew
                                                        Sep 29 '15 at 6:38







                                                      2




                                                      2





                                                      How would we go about doing getPart("fileattachments") so we get an array of Parts instead? I don't think getPart for multiple files will work?

                                                      – CyberMew
                                                      Sep 29 '15 at 6:38





                                                      How would we go about doing getPart("fileattachments") so we get an array of Parts instead? I don't think getPart for multiple files will work?

                                                      – CyberMew
                                                      Sep 29 '15 at 6:38











                                                      -2














                                                      HTML PAGE



                                                      <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>


                                                      SERVLET FILE



                                                      // Import required java libraries
                                                      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 = 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( 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.");




                                                      web.xml



                                                      Compile above servlet UploadServlet and create required entry in web.xml file as follows.



                                                      <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>





                                                      share|improve this answer





























                                                        -2














                                                        HTML PAGE



                                                        <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>


                                                        SERVLET FILE



                                                        // Import required java libraries
                                                        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 = 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( 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.");




                                                        web.xml



                                                        Compile above servlet UploadServlet and create required entry in web.xml file as follows.



                                                        <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>





                                                        share|improve this answer



























                                                          -2












                                                          -2








                                                          -2







                                                          HTML PAGE



                                                          <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>


                                                          SERVLET FILE



                                                          // Import required java libraries
                                                          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 = 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( 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.");




                                                          web.xml



                                                          Compile above servlet UploadServlet and create required entry in web.xml file as follows.



                                                          <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>





                                                          share|improve this answer















                                                          HTML PAGE



                                                          <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>


                                                          SERVLET FILE



                                                          // Import required java libraries
                                                          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 = 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( 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.");




                                                          web.xml



                                                          Compile above servlet UploadServlet and create required entry in web.xml file as follows.



                                                          <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>






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Jul 15 '16 at 13:28

























                                                          answered Jul 15 '16 at 7:14









                                                          Himanshu PatelHimanshu Patel

                                                          1099




                                                          1099















                                                              protected by BalusC May 20 '12 at 12:44



                                                              Thank you for your interest in this question.
                                                              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                              Would you like to answer one of these unanswered questions instead?



                                                              Popular posts from this blog

                                                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                                              은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현