Servlet 代碼:
複製代碼 代碼如下:
/** 直接取上傳的File */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String targetPath = request.getRealPath(request.getContextPath()); // 目標儲存路徑,伺服器部署目錄下
request.setCharacterEncoding("UTF-8");
try {
DefaultFileItemFactory factory = new DefaultFileItemFactory();
DiskFileUpload up = new DiskFileUpload(factory);
List<FileItem> ls = up.parseRequest(request);
for (FileItem file : ls) {
if (file.isFormField()) { // 判斷是檔案還是文本資訊
System.out.println("表單參數名:" + file.getFieldName()+ ",表單參數值:" + file.getString("UTF-8"));
} else {
if (file.getName() != null && !file.getName().equals("")) { // 判斷是否選擇了檔案
File sFile = new File(file.getName());// 構造臨時對象,此時檔案暫存在伺服器的記憶體當中
File tFile = new File(targetPath, sFile.getName());
if(tFile.exists()){
System.out.println("同名檔案已上傳!");
}else{
//FileUtils.copyFileToDirectory(sFile, tFile);//直接複製並上傳到伺服器,自動產生上機目錄,目錄名稱與上傳檔案的名稱一致
FileUtils.copyFile(sFile, tFile); // 直接複製並上傳檔案到伺服器,直接在指定位置產生目標檔案
System.out.println("檔案上傳成功");
if (tFile.isDirectory()) { // 刪除上傳檔案
FileUtils.deleteDirectory(tFile);
} else if (tFile.isFile()) {
tFile.delete();
}
System.out.println("檔案刪除成功");
}
} else {
System.out.println("沒有選擇上傳檔案!");
}
}
}
} catch (FileUploadException e) {
System.out.println("檔案上傳失敗!");
e.printStackTrace();
}
}
Servlet配置:web.xml
複製代碼 代碼如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>test.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/servlet/MyServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Html頁面:
複製代碼 代碼如下:
<body>
<form method="post" action="servlet/MyServlet" encType="multipart/form-data" >
<font color="blue">可直接發布zip檔案</font> <br />
發布流程檔案 :<input type="file" name="processDef" />
<input type="submit" value="部署"/>
</form>
</body>