0

Apache Commons FileUpload を使用して、サーブレットにファイルをアップロードできます。以下のコードは、サーブレットの processRequest メソッドで機能しましたが、コードを doPost メソッドにコピーして貼り付けたところ、機能しなくなりました。この線

 List fileItems = upload.parseRequest(request);

fileItems の空の配列を作成します。どうすればいいの?

ここに完全な doPost メソッドがあります

@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<FileItem> 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") >= 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("\\") >= 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);

}

そして、これはJSPです

 <%@ 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>
 <title>File Uploading Form</title>
 </head>
 <body>
 <h3>File Upload:</h3>
 Select a file to upload: <br />
 <form action="/Racing/UploadServlet" method="post"
                    enctype="multipart/form-data">
 <input type="file" name="file"  />
 <br />
 Logische Naam: <input type="text" name="logicalName"><br>
 Stuknr(automatisch,nog niet geimplementeerd): <input type="text" name="partNr"><br>
 Kost: <input type="text" name="cost"><br>


 Assembly:
<select name = "assembly">
 <c:forEach var ="assembly" items="${Assemblys}">
  <option value="${assembly.id}">${assembly.name}</option>
 </c:forEach>
</select>
<br>
<textarea name="comments" cols="25" rows="5">
Verdediging Design
</textarea><br>

<input type="submit" value="Upload File" />

</form>
</body>
</html>

よろしくお願いします!

4

1 に答える 1