表單:
<form action="A" method="post" enctype="multipart/form-data"> <!-- 是上傳表單 -->
使用者名:<input type="text" name="username"><br/>
檔案:<input type="file" name="file1"><br/>
<input type="submit" value="送出">
</form>
Servlet:
public class Servlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.建立檔案上傳工廠類
DiskFileItemFactory fac = new DiskFileItemFactory();
//2.建立檔案上傳核心類
ServletFileUpload upload = new ServletFileUpload(fac);
//[設定單個檔案最大上傳大小:30M]
upload.setFileSizeMax(30*1024*1024);
//[設定總的檔案最大上傳大小:50M]
upload.setSizeMax(50*1024*1024);
//判斷表單是否為檔案上傳表單
if(upload.isMultipartContent(request)){
//3.把請求資料轉換為FileItem對象集合
try {
List<FileItem> items = upload.parseRequest(request);
//周遊每一個上傳項
for(FileItem item:items){
//再判斷是普通表單還是檔案上傳表單
if(item.isFormField()){
//普通表單
System.out.println("普通表單");
//擷取元素名稱
String fileName = item.getFieldName();
//擷取文本框的值
String value = item.getString("UTF-8");
System.out.println(fileName+":"+value);
}else{
//處理檔案上傳
//擷取上傳檔案的名字
String name = item.getName();
System.out.println(name);
//擷取上傳的目錄路徑,指定檔案存儲路徑
String basePath = "G:/IntelliJ IDEA 2018.2.4/DynamicWeb/src/"; /*絕對路徑,存放到伺服器中的路徑*/
//建立檔案對象
File file = new File(basePath,name);
try {
item.write(file);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//寫檔案
item.delete();//删除臨時檔案
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println("檔案上傳異常,不處理!");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
将表單送出到Servlet後,即可實作本地檔案上傳至指定的伺服器目錄。