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

Viewed 26980

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 Answers
Related