how to upload and display profile picture using jsp and servelet.

Dani AI

Generated

Good question, and +1 to for asking where you plan to store it. If you are on Tomcat, the simplest and safest pattern is:

  • store the file on disk in a per-user directory that lives outside the webapp, and
  • store only the relative URL/path in your DB.

Do not write into your WAR or use getRealPath(...) for uploads; those files can disappear on redeploy. Instead, pick a fixed folder (for example under catalina.base) and create a directory per username. Modern containers support multipart natively, so you do not need Commons FileUpload unless you are on a very old servlet API.

Example servlet (Servlet 3.0+/JSP compatible). Your form must use enctype="multipart/form-data" and the file input name below is photo.

// /uploadProfile mapped in web.xml or with @WebServlet
@MultipartConfig(maxFileSize = 2_000_000, maxRequestSize = 3_000_000)
public class UploadProfileServlet extends HttpServlet {
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String user = (String) req.getSession().getAttribute("username");
    Part part = req.getPart("photo");
    if (user == null || part == null || part.getSize() == 0 ||
        part.getContentType() == null || !part.getContentType().startsWith("image/")) {
      resp.sendError(400, "Invalid upload");
      return;
    }

    Path base = Paths.get(System.getProperty("catalina.base"), "user-content");
    Path userDir = base.resolve(user).normalize();
    Files.createDirectories(userDir);

    // keep it simple: always overwrite the current profile picture
    String ext = part.getContentType().equals("image/png") ? ".png" : ".jpg";
    Path dest = userDir.resolve("profile" + ext);
    try (InputStream in = part.getInputStream()) {
      Files.copy(in, dest, StandardCopyOption.REPLACE_EXISTING);
    }

    // Save only the relative path like "/user-content/{user}/profile.jpg" in your DB
    resp.sendRedirect("profile.jsp");
  }
}

To display it later, read the path from your DB and use an <img> tag. You can either expose user-content as a static directory from Tomcat or stream the file via a small servlet that performs access checks. Validate file type and size, sanitize the username, and consider generating a random filename if you want to keep upload history.

Recommended Answers

All 7 Replies

it'll take a bit more effort than just asking this.
how do you want to upload? to the server? to a db?

i want to upload image to tomcat server by creating a folder with username and upload image to username and imagepath to database to retreive image easily.i want code in jsp or servelet.

so .. you want to upload it both to your server and to a db? what's the point of that?

what have you got so far?

i am getting folder with username but its not uploading image to username folder.please give the code i am working with social networking site so i want this code.

i want to upload image to tomcat server by creating a folder with username and upload image to username and only imagepath to database to retreive image easily.i want code in jsp or servelet.

so ... write the code.

<%@page import="javax.swing.text.Utilities"%>
<%@page import="org.apache.commons.io.FilenameUtils"%>
<%@page import="java.sql.*"%>

<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.util.*, java.io.*" %>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.util.List"%>
<%@ page import="java.io.File"%>
<%@ page contentType="text/html;charset=UTF-8" %>

<%

/*String ImageFile="";
String itemName = "";
String user = session.getAttribute("username").toString();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart)
{
}
else
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException e)
{
e.getMessage();
}

Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
if (item.isFormField())
{
String name = item.getFieldName();
String value = item.getString();
if(name.equals("ImageFile"))
{
ImageFile=value;
}

}
*/
//else
//{
      File savedFile;
    String destination;

    List<FileItem> items = null;
    try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    for (FileItem item : items) {
        if (item.isFormField()) {
            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
        } else {

           String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getName());
            InputStream fileContent = item.getInputStream();
            String userName = session.getAttribute("username").toString();
 File savedFile1 = new File(config.getServletContext().getRealPath("/")+"uploadedFiles/"+userName+".jpeg" );
          //  String fileName1="/" +"uploadedFiles/" + userName + ".jpeg";
 //destination = getServletContext().getRealPath(fileName);
// savedFile = new File(destination);

    if(! savedFile1.exists()) 
         savedFile1.mkdir();
    // savedFile1=new File( savedFile1 + "/" ); 
     // savedFile1.createNewFile();
     //  item.write(savedFile1);

File uploadedFile = new File("savedFile" );
                        System.out.println(uploadedFile.getAbsolutePath());
                        item.write(savedFile1);
     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savedFile1));
      byte[] buffer = new byte[1024];
            int len;

            //Read from file and write to new file destination
            while((len = fileContent.read(buffer)) >= 0) {
                bos.write(buffer, 0, len);
            }
             fileContent.close();
            bos.close();

}
    }

try
{

    Class.forName("com.mysql.jdbc.Driver");

Connection  con=DriverManager.getConnection("jdbc:mysql://localhost:3306/classified","root","12345");
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into image (image) values (?)");
 response.sendRedirect("welcomeuser.jsp");
}
catch(Exception el)
{
out.println("Inserting error"+el.getMessage());
}
}
}
catch (Exception e){
out.println(e.getMessage());
}
%>
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.