Refresh Your Java - Before Java Interview
We are Agile, believe in less Documentation - Only Quick notes (Java Interview Questions) of Java/J2ee Read more....
There are several ways of doing this, below are some of them.
By using 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()) {
String fieldname =
item.getFieldName();
String fieldvalue =
item.getString();
// Write Your logic
} else
{
// Process form file field (input
type="file").
String fieldname =
item.getFieldName();
String filename =
FilenameUtils.getName(item.getName());
InputStream filecontent =
item.getInputStream();
// Write Your logic
}
}
} catch
(FileUploadException e) {
throw new
ServletException("Cannot parse multipart
request.", e);
}
}
By using Servlet 3.0 MultipartConfig
import
java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import
java.util.Enumeration;
import
jakarta.servlet.ServletException;
import
jakarta.servlet.annotation.MultipartConfig;
import
jakarta.servlet.annotation.WebServlet;
import
jakarta.servlet.http.HttpServlet;
import
jakarta.servlet.http.HttpServletRequest;
import
jakarta.servlet.http.HttpServletResponse;
import
jakarta.servlet.http.Part;
@WebServlet(urlPatterns =
"/MultipartUploadServlet", name =
"MultipartUploadServlet")
@MultipartConfig(location = "/tmp", maxFileSize
= 10485760L)
public class MultipartYourUploadServlet
extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse
resp)
throws ServletException, IOException {
try {
Enumeration<String> hn = req.getHeaderNames();
while (hn.hasMoreElements()) {
String n = hn.nextElement();
System.out.println(n + " [" + req.getHeader(n) +
"]");
}
Collection<Part> requestParts =
req.getParts();
InputStream is = req.getInputStream();
int charRead = 0;
System.out.println("[");
while ((charRead = is.read()) != -1) {
System.out.print((char) charRead);
}
is.close();
System.out.println("]");
} catch (Exception excp) {
excp.printStackTrace();
}
}
}
This Portal is intended to put all Java/J2ee related topics at one single place for quick referance, not only Technical , but also the Project Management Related thing such as Development Process methodoogies build process, unit testing etc.,
This Portal has More than 500 Java Interview Questions (also could be Considered as Quick Notes) very neatly separated topic by topic with simple diagrams which makes you easily understandable. Importantly these are from our Realtime expericance.