jsp servlet文件上传doGet

时间:2013-01-28 04:38:44

标签: java jsp servlets file-upload apache-commons

我可以使用apache commons FileUpload在servlet中上传文件。下面的代码在servlet的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>

非常感谢提前!

1 个答案:

答案 0 :(得分:1)

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

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

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

    无需再次处理请求。

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

  3. 更改您的方法,使其如下所示:How to upload files to server using 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)构造函数。