Note that there are some explanatory texts on larger screens.

plurals
  1. POjsp servlet file upload doGet
    text
    copied!<p>I can upload a file in a servlet using the apache commons FileUpload. The code below worked in the processRequest method off the servlet, but I copy Pasted the code in the doPost method and now it doesn't work anymore. the line</p> <pre><code> List fileItems = upload.parseRequest(request); </code></pre> <p>makes an empty array of fileItems. How can this be?</p> <p>Here is the full doPost method</p> <pre><code>@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int fileId = 0; String LogicalName = ""; String PartNr = ""; String Cost = ""; String Assembly = ""; String Comment = ""; try { Connection conn = MysqlConnect.conn(); List&lt;FileItem&gt; items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { //als het een veld is dan dit, anders File uploaden String fieldname = item.getFieldName(); String fieldvalue = item.getString(); switch (fieldname) { case "logicalName": LogicalName = fieldvalue; break; case "partNr": PartNr = fieldvalue; break; case "cost": Cost = fieldvalue; break; case "assembly": Assembly = fieldvalue; break; case "comments": Comment = fieldvalue; break; } } else { PrintWriter out = response.getWriter(); File file; int maxFileSize = 500000 * 1024;//max 500 mb groot int maxMemSize = 5000 * 1024;//max 5mb gecached in het ram,indien file groter is eerst wegschrijven in een temp dir String filePath = "C:\\uploads\\"; String fileName = ""; String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") &gt;= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); factory.setRepository(new File("c:\\temp")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); try { List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { String fieldName = fi.getFieldName(); fileName = fi.getName(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); if (fileName.lastIndexOf("\\") &gt;= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); } } HttpSession session = request.getSession(); int uploader = (Integer) session.getAttribute("UserId"); String Query = "Insert into tbl_file (fileLocation,Uploader)values(\"" + fileName + "\"," + uploader + ");"; PreparedStatement st = conn.prepareStatement(Query, Statement.RETURN_GENERATED_KEYS); st.executeUpdate(); ResultSet rs = st.getGeneratedKeys(); if (rs.next()) { fileId = rs.getInt(1); } } catch (Exception ex) { System.out.println(ex); } } } } if (fileId == 0) { //ERROR } else { Statement stmt = conn.createStatement(); String Query1 = "Insert into tbl_part (partCad,partCost,partAssembly,partMotivation,partOf) VALUES(" + fileId + "," + Cost + "," + Assembly + ",\"" + Comment + "\"," + "1" + ");"; stmt.executeUpdate(Query1); } MysqlConnect.close(conn); } catch (SQLException ex) { Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (FileUploadException e) { throw new ServletException("Cannot parse multipart request.", e); } String URL = "/home.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(URL); dispatcher.forward(request, response); } </code></pre> <p>And This is the JSP</p> <pre><code> &lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;File Uploading Form&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h3&gt;File Upload:&lt;/h3&gt; Select a file to upload: &lt;br /&gt; &lt;form action="/Racing/UploadServlet" method="post" enctype="multipart/form-data"&gt; &lt;input type="file" name="file" /&gt; &lt;br /&gt; Logische Naam: &lt;input type="text" name="logicalName"&gt;&lt;br&gt; Stuknr(automatisch,nog niet geimplementeerd): &lt;input type="text" name="partNr"&gt;&lt;br&gt; Kost: &lt;input type="text" name="cost"&gt;&lt;br&gt; Assembly: &lt;select name = "assembly"&gt; &lt;c:forEach var ="assembly" items="${Assemblys}"&gt; &lt;option value="${assembly.id}"&gt;${assembly.name}&lt;/option&gt; &lt;/c:forEach&gt; &lt;/select&gt; &lt;br&gt; &lt;textarea name="comments" cols="25" rows="5"&gt; Verdediging Design &lt;/textarea&gt;&lt;br&gt; &lt;input type="submit" value="Upload File" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Many thanks in advance!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload