这不行.问题是我甚至不知道应该发生什么.我无法调试此代码.我想将上传存储到临时文件夹"temp",然后将它们移动到"applets".请帮忙?显然正在访问servlet,但我无法找到上传的文件...在此先感谢.
表单(使用scriptlet创建 - 如果可能导致问题,我将其放在此处):
<% out.write(""); %>Upload a new game:
"); out.write("
哪个叫这个javascript:
function submitToServlet2(newAction) { document.uploadForm.action = newAction; }
反过来又转到servlet(代码包含在full中,因为可能有一些重要的元素隐藏)
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 HTTPGET
andPOST
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(""); out.println(""); out.println("Servlet UploadGameServlet "); out.println(""); out.println(""); out.println("Servlet UploadGameServlet at " + request.getContextPath () + "
"); out.println(""); out.println(""); } finally { out.close(); } }
}
File repositoryPath = new File("\\temp"); File uploadedFile = new File("\\applets");
通过尝试在没有任何前导或绝对路径的情况下访问这些文件,您尝试写入命名的文件(而不是目录)temp
并applets
在当前工作目录下.在应用服务器中,当前工作目录通常是bin
文件夹(取决于您使用的应用服务器等).
一些建议:
使用绝对路径(最好存储在web.xml或属性文件中)来引用要保存文件的目录.
您必须指定要写入的文件的名称,您可能希望为每个请求创建某种随机/唯一名称.
保存一些键击并使用成员变量而不是所有Logger.getLogger(UploadGameServlet.class.getName())
引用!
添加一些调试,尤其是查看您将数据写入的位置 - repositoryPath.getAbsolutePath()
例如,记录结果.