how can i make a servlet to validate a form with two file upload one image and other a pdf file. along with the other string parameters like name age gender etc.,

i need to validate the pdf and image files in servlet and save it in folder of my project, and the path and other parameters in database.

please help..!!

i need to do in servlets only first then will try in struts.

Dani AI

Generated

Brief, practical plan for — and a sanity-check on the existing replies. ’s manual byte-parsing is brittle and error-prone; ’s pointer to libraries is valid. A safer, maintainable servlet-first approach: accept the uploaded Parts, stream each to a temporary file, validate the file contents (not just the Content-Type header), then atomically move the file to a permanent directory outside the WAR and record the path + metadata in the database inside a transaction.

Example (robust workflow: temp → validate → move → DB). Save each Part to a temp file, check signatures and content (for images try ImageIO.read; for PDF check the "%PDF" header), then move to final location with a generated UUID name. Use PreparedStatement and commit only after the file move succeeds; if the DB insert fails, delete the moved file.

@MultipartConfig(fileSizeThreshold=1024*1024, maxFileSize=10*1024*1024)
public class UploadServlet extends HttpServlet {
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    Part imgPart = req.getPart("image");
    Part pdfPart = req.getPart("pdf");
    Path uploads = Paths.get("/opt/app/uploads");
    Files.createDirectories(uploads);

    Path tmpImg = Files.createTempFile("img-", ".tmp");
    try (InputStream in = imgPart.getInputStream()) { Files.copy(in, tmpImg, REPLACE_EXISTING); }
    if (ImageIO.read(tmpImg.toFile()) == null) { Files.deleteIfExists(tmpImg); throw new ServletException("Invalid image"); }

    Path tmpPdf = Files.createTempFile("pdf-", ".tmp");
    try (InputStream in = pdfPart.getInputStream()) { Files.copy(in, tmpPdf, REPLACE_EXISTING); }
    byte[] h = new byte[4];
    try (InputStream is = Files.newInputStream(tmpPdf)) { if (is.read(h) != 4 || !new String(h,0,4,US_ASCII).equals("%PDF")) { Files.deleteIfExists(tmpPdf); throw new ServletException("Invalid PDF"); } }

    Path finalImg = uploads.resolve(UUID.randomUUID().toString()+".img");
    Path finalPdf = uploads.resolve(UUID.randomUUID().toString()+".pdf");
    Files.move(tmpImg, finalImg, ATOMIC_MOVE);
    Files.move(tmpPdf, finalPdf, ATOMIC_MOVE);

    // then insert finalImg.toString()/finalPdf.toString() + other params into DB (use transaction; delete files if DB fails)
  }
}

Practical tips and caveats: enforce server-side size limits (annotation or library config), sanitize and never trust client filenames, generate unique names, keep uploads outside the webapp (redeploys wipe WAR content), ensure directory write permissions, handle IllegalStateException when limits are exceeded, and always clean up temp files on any error. If Servlet 3.x multipart support isn’t available, use Apache Commons FileUpload as suggested by .

Recommended Answers

All 3 Replies

Sorry i cannot help you,i still have a very long way to run to be right where you are.I hope you will find your answer.

i think following code might be useful or you can get the idea what to do.

%@page import="java.io.*, java.sql.*"%>
<%

String saveFile="";
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
saveFile="C:/UploadedFiles/"+saveFile;
File f = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(f);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
%>
    <b>You have successfully upload the file by the name of:</b>
     <%
 out.println(saveFile);
   }
%>


First you need to declare content type as ""multipart/form-data" on your jsp.

 <form action="uploadResume" method="post" enctype="multipart/form-data"> 

then using simple html tag

<input type="file">

you can provide provision for file upload on jsp.

For validation you need to write java script code on the jsp.

In servlet you need to use package "org.apache.commons.fileupload" to handle the uploaded file.
below are the links that explains all i have mentioned above.

http://commons.apache.org/fileupload/using.html

Even on apche's oficial site there are examples how to use "org.apache.commons.fileupload"

I have used this package in my project for similar requirement.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.