/** 直接取上傳的File */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String targetPath = request.getRealPath(request.getContextPath()); // 目標(biāo)存儲(chǔ)路徑,服務(wù)器部署目錄下
request.setCharacterEncoding("UTF-8");
try {
DefaultFileItemFactory factory = new DefaultFileItemFactory();
DiskFileUpload up = new DiskFileUpload(factory);
ListFileItem> ls = up.parseRequest(request);
for (FileItem file : ls) {
if (file.isFormField()) { // 判斷是文件還是文本信息
System.out.println("表單參數(shù)名:" + file.getFieldName()+ ",表單參數(shù)值:" + file.getString("UTF-8"));
} else {
if (file.getName() != null !file.getName().equals("")) { // 判斷是否選擇了文件
File sFile = new File(file.getName());// 構(gòu)造臨時(shí)對(duì)象,此時(shí)文件暫存在服務(wù)器的內(nèi)存當(dāng)中
File tFile = new File(targetPath, sFile.getName());
if(tFile.exists()){
System.out.println("同名文件已上傳!");
}else{
//FileUtils.copyFileToDirectory(sFile, tFile);//直接復(fù)制并上傳到服務(wù)器,自動(dòng)生成上機(jī)目錄,目錄名稱與上傳文件的名稱一致
FileUtils.copyFile(sFile, tFile); // 直接復(fù)制并上傳文件到服務(wù)器,直接在指定位置生成目標(biāo)文件
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();
}
}
?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>