1:文件上傳時,上傳到webapps目錄下的文件會自動刪除的原因?
tomcat目錄下的webapps 文件夾是部署目錄,當項目重新部署(Tomcat重啟、代碼改變時的自動部署),上傳的文件不在部署文件的范疇內,即此時開發工具中沒有上傳的文件,所以上傳的文件就沒有了。
清理緩存也會使上傳到webapps目錄下的文件文件消失。
2:解決方法
把文件上傳路徑設置到webapps目錄之外,可以在Tomcat目錄下建立一個文件夾,如:upload
3:簡單實現
html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="../jsp/smartupload.jsp" method="post" enctype="multipart/form-data"><input type="file" name="file"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
jsp文件:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.jspsmart.upload.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<% SmartUpload smart=new SmartUpload(); smart.initialize(pageContext); smart.upload(); //將文件上傳到項目目錄下,重新部署后會自動消失 //smart.save(request.getSession().getServletContext().getRealPath("/")+"/upload"); //通過絕對路徑將文件上傳到Tomcat目錄下的upload文件夾內,則重新部署后不會消失 smart.save("D:\\software\\learningsoftware\\tomcat\\apache-tomcat-7.0.72\\upload"); %>
</body>
</html>
此外,直接在Tomcat/webappps目錄下的項目文件中添加文件、在lib中放入jar包、修改web.xml,配置server.xml等,當Tomcat重啟(或代碼改變時自動部署),eclipse就會重新部署項目,或者清理緩存后,那么直接在webapps下的項目目錄中進行的操作就失效了。
解決方法:
一:直接在eclipse中進行操作
如:直接在eclipse中的web項目下添加文件,導入jar包(直接復制粘貼,再build path-add to build path),修改web.xml文件,在servers項目中修改server.xml等,即便重新部署這些操作也不會消失,因為這些內容已經存在於eclipse中了。
二:取消eclipse的自動發布功能
Window->Preferences->Server->Launching->點擊取消Automatically publish wen starting servers