How to upload file using Servlet of Java in NetBeansIDE -- part 1

Опубликовано: 01 Март 2014
на канале: raksrahul
11,491
14

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 :)

Follow us on :
Facebook :   / raksrahul-100219708647780  
Instagram :   / raksrahul_ig  


#java #netbeanside #programming #coding #developer #tips #tricks