我上传的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);
}
我的系统总是说文件和目的地都存在。我正试图让上传覆盖现有文件。
完整代码:(& pastebin)
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”不在代码中,这只是为了保护我的家庭路径
答案 0 :(得分:0)
经过多次测试和加重,最后在不同的机器上尝试了它,相同的代码,效果很好。与我在工作机器上传输域名有关,而且它与权限相关。