How to upload file using Servlet of Java in NetBeansIDE


How to upload file using Servlet of Java in NetBeansIDE


How to upload file using Servlet of Java in NetBeansIDE

1. Open NetBeansIDE.

2. Make a new Java web project.

3. Make a form in index.jsp (method='POST', enctype='multipart/form-data').

4. Make a servlet(FileUploadServlet) in source package folder and add it to deployment
   descriptor(web.xml).

5. Copy this process request method code in your servlet.

protected void processRequest(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    final String path = request.getParameter("destination");
    final Part filePart = request.getPart("file");
    final String fileName = getFileName(filePart);

    OutputStream out = null;
    InputStream filecontent = null;
    final PrintWriter writer = response.getWriter();

    try {
        out = new FileOutputStream(new File(path + File.separator + fileName));
        filecontent = filePart.getInputStream();

        int read = 0;
        final byte[] bytes = new byte[1024];

        while ((read = filecontent.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        writer.println(fileName + " created at " + path);

    } catch (FileNotFoundException fne) {
        writer.println("Error in file upload  ERROR:" + fne.getMessage());

    } finally {
        if (out != null) {
            out.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

private String getFileName(final Part part) {
    final String partHeader = part.getHeader("content-disposition");
    for (String content : part.getHeader("content-disposition").split(";")) {
        if (content.trim().startsWith("filename")) {
            return content.substring(
                    content.indexOf('=') + 1).trim().replace("\"", "");
        }
    }
    return null;
}

6. Add @MultipartConfig annotation on your servlet class.

7. Fix all imports as per this tutorial.

8. Run the Project.

9. Finish.

Thank You :)

Comments

  1. Sir i performed the same steps as u performed but m facing an error which is something like this
    HTTP Status 404 - Not Found

    type Status report

    messageNot Found

    descriptionThe requested resource is not available.

    GlassFish Server Open Source Edition 4.0

    M seriously troubled by this ..plzz help

    ReplyDelete
    Replies
    1. http status as 4xx means error from client side.

      check if u are typing right url

      Delete

Post a Comment

Popular posts from this blog

How to Detect CapsLock key using Java in NetBeansIDE.

How to Perform DES Encryption and Decryption of TXT file in JAVA with NetBeansIDE

How to insert Image in MySQL Database with Java in NetBeansIDE