Hi im new to jsp and I was wondering anybody could help me about uploading images using jsp.

Dani AI

Generated

Short answer: keep the upload form in a JSP (view) and do the multipart processing in a servlet (controller). 's core point about using servlets is correct: JSPs are for presentation, not for handling binary uploads or file I/O. The sketch below covers a safe, maintainable flow and practical tips for both modern containers and older ones.

Recommended flow and checks:

  1. Present an HTML form with method="post" and enctype="multipart/form-data".
  2. Handle the POST in a servlet — either the Servlet 3+ Part API (built-in multipart handling) or Apache Commons FileUpload for older containers.
  3. Validate size and type (check MIME and, when practical, inspect file header bytes), sanitize filenames, and generate unique server-side names (UUIDs).
  4. Persist uploads outside the webapp directory (so redeploys do not delete files) and serve them through a mapped servlet or static file handler with proper content-type and caching headers.
  5. Configure limits (multipart max sizes), logging, and graceful error responses.

Example (UI + a common-server approach using Apache Commons FileUpload):

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

DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(MAX_REQUESTSIZE);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
File dir = new File("/var/data/uploads");
if (!dir.exists()) dir.mkdirs();
File saved = new File(dir, UUID.randomUUID().toString() + "
" + fileName);
item.write(saved);
}
}

Security and troubleshooting notes: enforce server-side size limits (Tomcat/servlet container can impose limits), refuse unexpected MIME types, scan for viruses if required, and never trust client-supplied filenames (strip paths, normalize). If uploads seem ignored, confirm the form enctype, servlet mapping, and container multipart settings. For authoritative guidance on libraries and hardening, see Apache Commons FileUpload and the OWASP File Upload Cheat Sheet: Apache Commons FileUpload and OWASP File Upload Cheat Sheet.

Recommended Answers

All 2 Replies

Try this.

Try this.

Somebody please, please give me a stick I want to beat them :twisted: .
Servlets, servlets and again servlets should be used for such tasks

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.