我的上传servlet不断给我一个例外,说我要替换的文件(在代码的末尾)无法在(看似)随机删除。我不知道是什么原因引起的,因为我没有使用任何流,并且该文件在浏览器中没有打开。有人知道会导致这一点吗?我对此完全毫无头绪,因为代码对我来说似乎是正确的。这是我第一次使用diskfileitem,所以我不确定是否有任何细微差别要处理。

请记住,有时可以工作,有时行不通。我迷路了。

问题区域:

File destination = new File(wellnessDir + File.separator + fileName + ".pdf");

  System.out.println("destination file exists: " + destination.exists());
  System.out.println("file to be moved exists: " + uploadedFile.exists());

  if(destination.exists()){
    boolean deleted = destination.delete();
    if(!deleted)
      throw new Exception("Could not delete file at " + destination);
  }        

我的系统出现总是说文件和目的地都存在。我正在尝试上传以覆盖现有文件。

完整代码:(& 粘贴)

private void uploadRequestHandler(ServletFileUpload upload, HttpServletRequest request)
  {
    // Handle the request
    String fileName = "blank";
    try{         
      List items = upload.parseRequest(request);
      //Process the uploaded items
      Iterator iter = items.iterator();
      File uploadedFile = new File(getHome() + File.separator + "temp");
      if(uploadedFile.exists()){
        boolean tempDeleted = uploadedFile.delete();
        if(!tempDeleted)
          throw new Exception("Existing temp file could not be deleted.");
      }
      //write the file
      while (iter.hasNext()) {
        DiskFileItem item = (DiskFileItem) iter.next();
        if(item.isFormField()){
          String fieldName = item.getFieldName();
          String fieldValue = item.getString();
          if(fieldName.equals("fileName"))
            fileName = fieldValue;
            //other form values would need to be handled here, right now only need for fileName
        }else{
          item.write(uploadedFile);
        }
      }
      if(fileName.equals("blank"))
        throw new Exception("File name could not be parsed.");
      //move file
      File wellnessDir = new File(getHome() + File.separator + "medcottage" + File.separator + "wellness");
      File destination = new File(wellnessDir + File.separator + fileName + ".pdf");

      System.out.println("destination file exists: " + destination.exists());
      System.out.println("file to be moved exists: " + uploadedFile.exists());

      if(destination.exists()){
        boolean deleted = destination.delete();
        if(!deleted)
          throw new Exception("Could not delete file at " + destination);
      }        
      FileUtil.move(uploadedFile, new File(wellnessDir + File.separator + fileName + ".pdf"));
      writeResponse();
    } catch (Exception e) {
      System.out.println("Error handling upload request.");
      e.printStackTrace();
    }
  }

编辑:添加,Gethome()和“ Home”并不是真正的代码中,这只是为了保护我的家庭道路

有帮助吗?

解决方案

经过大量的测试和加重,最终在另一台机器(相同的代码)上尝试了它,效果很好。与我在工作机器上转移域有关,这与权限有关。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top