Upload image and Save inside Web Content Folder in JSP and Save Image Path in Database

27.2k views Asked by At

My goal is to upload an image and save inside images folder to Web Content Folder.

{Please see the image below}

enter image description here

and save the image path into database

{Please see the image below}

enter image description here

I encountered some problem at this link I tried to do but I did not managed to save the image to images/users folder.

And I realize that the save path is store at my C DRIVE. What if I change my computer? Will the image will be there?

Below are my codes. Help will be appreciate.. Thanks! :)

In jsp

<input type="file" name="file">

In servlet

public class AServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String SAVE_DIR = "WebContent\\images\\users";

.........

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

     // gets absolute path of the web application
        String appPath = request.getServletContext().getRealPath("");
        // constructs path of the directory to save uploaded file
        String savePath = appPath + File.separator + SAVE_DIR;

        // creates the save directory if it does not exists
        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }

        for (Part part : request.getParts()) {
            String fileName = extractFileName(part);
            part.write(savePath + File.separator + fileName);
        }

System.out.println(savePath);

}

       private String extractFileName(Part part) {
            String contentDisp = part.getHeader("content-disposition");
            String[] items = contentDisp.split(";");
            for (String s : items) {
                if (s.trim().startsWith("filename")) {
                    return s.substring(s.indexOf("=") + 2, s.length()-1);
                }
            }
            return "";
        }
1

There are 1 answers

7
Sureshkumar Panneerselvan On

Follow the link provided by SasiKathimanda for code implementation.

Create the file name as 'OrignalFilename+SystemTimeInMills' in order to avoid overriding already uploaded file with same filename.

Otherwise check for duplicate filename before write filecontent to server.

Follow the pattern(For DB File Path) if you need to provide download option(later), otherwise you can save the uploaded absolute file path.