0

我可以使用 apache commons FileUpload 在 servlet 中上传文件。下面的代码在 servlet 的 processRequest 方法中工作,但我将代码复制到 doPost 方法中,现在它不再工作了。线

 List fileItems = upload.parseRequest(request);

生成一个空的文件项数组。怎么会这样?

这是完整的 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

1

您的代码行List fileItems = upload.parseRequest(request);甚至该else部分中的所有行都没有任何意义,因为:

  1. 您之前已经在此行中处理过请求

    List<FileItem> items = new ServletFileUpload(
        new DiskFileItemFactory()).parseRequest(request);
    

    无需再次处理请求。

  2. 您已经在方法返回 false的item对象中拥有想要/需要处理的文件。isFormField

更改您的方法,使其看起来像这里:如何使用 JSP/Servlet 将文件上传到服务器?

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.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;
            //other case statements...
        }
    } else {
        //here you only have to process the file
        File file;
        int maxFileSize = 500000 * 1024;//your comments...
        int maxMemSize = 5000 * 1024;//your comments...
        //this must be a constant or a servlet init param, do not hard code it
        String filePath = "C:\\uploads\\";
        String fileName = FilenameUtils.getName(item.getName());
        factory.setSizeThreshold(maxMemSize);
        //didn't you have a filePath variable?
        factory.setRepository(new File("c:\\temp"));
        upload.setSizeMax(maxFileSize);
        try {
            String fieldName = fi.getFieldName();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            file = new File(filePath, fileName);
            item.write(file);
            //code to save your file location in db...
            //note: this MUST BE in a business logic method, not directly written in your servlet
            HttpSession session = request.getSession();
            int uploader = (Integer) session.getAttribute("UserId");
        } catch (Exception ex) {
            //very BAD idea
            //use a logger instead like log4j or sfl4j
            System.out.println(ex);
        }
    }
}

附加:检查File(String parent, String child)构造函数。

于 2013-01-28T05:19:52.440 回答