前提要求
前端頁面要求
method=“post”
enctype=“multipart/form-data”
上傳檔案的input的type=“file”
每個上傳的元件必須有name屬性,這樣背景才能擷取到資料
<form action="/UploadServlet" method="post" enctype="multipart/form-data">
上傳檔案所要用到的類、接口和方法
由于我們上傳檔案到本地伺服器,需要解析請求到tomcat伺服器的内容,然後寫入本地目标檔案夾,我們手工操作,會花費大量的時間精力,可能還會因為一個标點符号或者其他出錯。是以為了友善我們使用apache上傳檔案的元件:需要導入兩個第三方包
下載下傳位址:Apache官網–project–commons–FileUpload
api:下載下傳的jar包中打開index.html(必須在下載下傳原目錄打開,我的預設C:\Users\Administrator\Downloads)
1.Apache-fileupload.jar – 檔案上傳核心包
2.Apache-commons-io.jar
ServletFileUpload類
主要用來解析request對象
常用方法
1、boolean isMultipartContent(HttpServletRequest req)
作用:determines whether the request contains multipart content.
3、**List parseRequest(HttpServletRequest req)throws FileUploadException
作用:解析request,結合DiskFileItemFactory,最終将form表單中的每個input标簽解析成一個一個的FileItem對象,存儲在List集合中
FileItemFactory接口
實作類
public DiskFileItemFactory()
作用:主要将form表單中的每個input标簽解析成一個一個的FileItem對象
FileItem接口
常用方法
1、boolean isFormField()
作用:判斷是不是普通表單
2、 getFieldName()
作用:Returns the name of the field in the multipart form corresponding to this file item.
(表單字段name屬性值)
3、 getName()
作用:Returns the original filename in the client’s filesystem, as provided by the browser (or other client software).(檔案上傳字段檔案名)
4、getString()
作用:Returns the contents of the file item as a String, using the default character encoding.
5、getString(String encoding)
作用:Returns the contents of the file item as a String, using the specified encoding.
6、write(File file)
作用:A convenience method to write an uploaded item to disk.
Servlet代碼
{
//設定編碼格式,
//普通的form,并且使用的post送出的資料編碼有效
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
/**
* 準備上傳所要用到的類
* DiskFileItemFactory,負責管理磁盤檔案
* ServletFileUpload,負責上傳和解析檔案
*/
//判斷表單enctype屬性是否為 multipart/form-data,
boolean multipartContent = ServletFileUpload.isMultipartContent(request);
if(!multipartContent){
//若不是,抛異常,也可以給使用者輸出提示
throw new RuntimeException("The form's enctype attribute value must be multipart/form-data");
}
//建立儲存檔案的路徑
//若是,得到form表單中的每個input元件(FileItem對象)
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
//解析
try {
List<FileItem> list = upload.parseRequest(request);
//周遊每一個FileItem
for (FileItem m:list
) {
//判斷它是不是普通元件
if(m.isFormField()){
//如果是普通元件,就輸出name屬性值
String name = m.getFieldName();
System.out.println("name="+name);
//得到value值,用重載的getString()方法解決編碼
String value = m.getString("UTF-8");
System.out.println("value="+value);
}else {
//如果是file類型元件,得到檔案名
String fileName = m.getName();
System.out.println("檔案名="+fileName);
//儲存進指定檔案
m.write(new File("E:\\"+fileName));
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}