0

There is an issue in the file uploading part.

Here is the code

<form action="uploadlogoc.jsp" method="post" enctype="multipart/form-data"> <table align="center"> <tr><td> USER:</td><td><select name="userDetails"> <% while(rs.next()){%> <option><%=rs.getString("username") %></option> <%} %> </select> </td></tr> <tr><td>Subject</td><td><input type="text" name="subject"/></td></tr> <tr> <td>File:</td><td><input type="file" name="file" size="25"></td> </tr> <tr><td></td><td><input type="submit" name="s1" value="Uploadfile"><td></td> </tr> </table> 

Values in the subject field and username field shouldn't be passed to next page, because of the presence of enctype. When we remove it value will pass,but file is not uploaded. What is the reason?

Connection cone=null; Statement smt=null; ResultSet rs=null; DbConnection con=new DbConnection(); try{ cone=con.Connection(); String sql="SELECT * FROM reg"; smt=cone.createStatement(); rs=smt.executeQuery(sql); } catch(Exception e){ e.printStackTrace(); } %> 
6
  • No notification of errors Commented Feb 15, 2015 at 10:43
  • can you show us uploadlogoc.jsp relevant code Commented Feb 15, 2015 at 10:44
  • uploadlogoc.jsp code? Commented Feb 15, 2015 at 10:45
  • Connection cone=null; Statement smt=null; ResultSet rs=null; DbConnection con=new DbConnection(); try{ cone=con.Connection(); String sql="SELECT * FROM reg"; smt=cone.createStatement(); rs=smt.executeQuery(sql); } catch(Exception e){ e.printStackTrace(); } %> Commented Feb 15, 2015 at 10:47
  • chat.stackoverflow.com/rooms/70951/file-uploading-in-jsp can u paste the code here Commented Feb 15, 2015 at 10:48

3 Answers 3

1

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> 

Sign up to request clarification or add additional context in comments.

Comments

0

you have to use request.getParts() instead of request.getParameter()

Comments

0

When we remove it value will pass,but file is not uploaded.

You can not remove enctype='multipart/form-data' , When you make a POST request, you have to encode the data that forms the body of the request in some way.

There are many ways of encoding POST request but , When you are writing client-side code, all you need to know is use multipart/form-data when your form includes any <input type="file"> elements.

Use encType and In your Servlet Class

Instead of Using

request.getParameter("parameterName");

use

MultipartRequest#getParameter("parametername");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.