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
Watch video How to upload file using Servlet of Java in NetBeansIDE -- part 1 online without registration, duration hours minute second in high quality. This video was added by user raksrahul 01 March 2014, don't forget to share it with your friends and acquaintances, it has been viewed on our site 11,491 once and liked it 14 people.