To upload a file,we must use enctype="multipart/form-data" but if use this along with some text fields,parsing of these fields(request.getParameter) returns null So we have to follow another procedure We will use form.jsp,upload.java,display.jsp
<html> <head></head> <body> <form action="upload" method="post" enctype="multipart/form-data"> Name:<input type="text" name="text"> <br> Select File to Upload:<input type="file" name="fileName"> <input type="submit" value="Upload"> </form> </body> </html>
package helper; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Part; import org.apache.commons.fileupload.util.Streams; /** * Servlet implementation class upload */ @WebServlet("/upload") @MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB maxFileSize=1024*1024*50, // 50 MB maxRequestSize=1024*1024*100) // 100 MB public class upload extends HttpServlet { private static final long serialVersionUID = 1L; private static final String UPLOAD_DIR = "new"; /** * @see HttpServlet#HttpServlet() */ public upload() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // gets absolute path of the web application String applicationPath = request.getServletContext().getRealPath(""); // constructs path of the directory to save uploaded file String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR; //Declare fields for storing parse values from user String name=""; //url which you will store in database String url=""; // creates the save directory if it does not exists File fileSaveDir = new File(uploadFilePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdirs(); } //Contains fileName String fileName = null; int i=0; //Get all the parts from request and write it to the file on server for (Part part : request.getParts()) { fileName = getFileName(part); InputStream stream=part.getInputStream(); if(!fileName.equals("NOT_AN_IMAGE")){ url=fileName; //Stores the file in the respective directory part.write(uploadFilePath + File.separator + fileName); } else{ String user_input=Streams.asString(stream); i++; switch(i){ case 1:name=user_input; break; } } } //Insert String url as path in the database HttpSession session=request.getSession(true); //Storing url of the current file which is uploaded as attribute String path=UPLOAD_DIR+"\\"+url; //Input text field name System.out.println(path); System.out.println(name); session.setAttribute("field", name); session.setAttribute("link",path); RequestDispatcher rd=request.getRequestDispatcher("display.jsp"); rd.forward(request,response); } //Finding whether it is file or text private String getFileName(Part part) { String contentDisp = part.getHeader("content-disposition"); System.out.println("content-disposition header= "+contentDisp); String[] tokens = contentDisp.split(";"); String msg="NOT_AN_IMAGE"; for (String token : tokens) { if (token.trim().startsWith("filename")) { return token.substring(token.indexOf("=") + 2, token.length()-1); } } return msg; } }
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body align="center"> <h1 align="center"> <c:out value="${sessionScope.field}"/></h1> <img src=<c:out value="${sessionScope.link}"/> width="306" height="208"> </body> </html>