1

I want to upload image along with data from jsp form. Then send these values to servlet. My code for jsp form is as following:

<form action="AddController" method="post" name="addform" id="addform"  >
Name : <input type="text" name="myname">
Image : <input type="file" accept="image/*" name="file">
<input type="submit" name="add" id="add" value="Save"/>
</form>

The code for servlet is as following. The code :

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

    String add=request.getParameter("add");
    if(add!=null) {

    String name =request.getParameter("myname");
    System.out.println(myname);

    String SAVE_DIR = "C:/uploadFiles";
    // gets absolute path of the web application
    String appPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    String savePath =  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);
    }

    request.setAttribute("message", "Upload has been done successfully!");
    getServletContext().getRequestDispatcher("/addsuccessful.jsp").forward(
            request, response);
}
}
/**
 * Extracts file name from HTTP header content-disposition
 */
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 "";
}

I get the name value from text box. But image is not uploaded. When I add enctype="multipart/form-data" in form then I am not getting name value. How to solve this issue????

user3598397
  • 55
  • 1
  • 5
  • At the very least you should be able to understand the difference between the JSP and the HTML that is generated by it... – SJuan76 Oct 22 '14 at 12:12

0 Answers0