这只是行不通的。问题是我不知道该怎么办。我无法调试此代码。我想将上传内容存储到临时文件夹“ temp”,然后将其移至“ applets”。请帮忙?显然,正在访问servlet,但是我找不到上载的文件。
表单(使用脚本创建的表单-如果可能导致问题,我将其放在此处):
<% out.write("<p>Upload a new game:</p>"); out.write("<form name=\"uploadForm\" action=\"game.jsp\" " + "method=\"POST\" enctype=\"multipart/form-data\">" + "<input type=\"file\" name=\"uploadSelect\" value=\"\" width=\"20\" />" + "<br><input type=\"submit\" value=\"Submit\" name=\"uploadSubmitButton\" " + "onclick = \"submitToServlet2('UploadGameServlet');\">" + "</form>"); %>
哪个调用此javascript:
function submitToServlet2(newAction) { document.uploadForm.action = newAction; }
依次转到servlet(完整的代码,因为可能隐藏了一些重要的元素)
package org.project; import java.io.*; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; // import servlet stuff import org.apache.commons.fileupload.*; public class UploadGameServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); if (ServletFileUpload.isMultipartContent(request)) { try { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest(request); /* FileItem */ File repositoryPath = new File("\\temp"); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(repositoryPath); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); File uploadedFile = new File("\\applets"); item.write(uploadedFile); } } catch (FileUploadException ex) { Logger.getLogger(UploadGameServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(UploadGameServlet.class.getName()).log(Level.SEVERE, null, ex); } } PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet UploadGameServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet UploadGameServlet at " + request.getContextPath () + "</h1>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } }
}
File repositoryPath = new File("\\temp"); File uploadedFile = new File("\\applets");
试图访问这些文件,而无需任何形式的领导或绝对路径,你正在试图写入指定的文件(不是目录)temp和applets当前工作目录下。在应用服务器中,当前工作目录通常是bin文件夹(取决于您使用的应用服务器等)。
temp
applets
bin
一些建议:
Logger.getLogger(UploadGameServlet.class.getName())
repositoryPath.getAbsolutePath()