一、什麼是fileUpload?
fileUpload是apache的commons元件提供的上傳元件,它最主要的工作就是幫我們解析request.getInpustream()。可以參考線上API文檔:http://tool.oschina.net/apidocs/apidoc?api=commons-fileupload
二、fileupload元件工作原理
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5CNwYDOwIjY5QDN5YWM0Q2MxEWNkdTOiJzNzUGNjJTZx8CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
三、fileupload核心API
1. DiskFileItemFactory
構造器
1) DiskFileItemFactory() // 使用預設配置
2) DiskFileItemFactory(int sizeThreshold, File repository)
sizeThreshold 記憶體緩沖區, 不能設定太大, 否則會導緻JVM崩潰
repository 臨時檔案目錄
2. ServletFileUpload
1) isMutipartContent(request) // 判斷上傳表單是否為multipart/form-data類型 true/false
2) parseRequest(request) // 解析request, 傳回值為List類型
3) isFormField() //是否是普通檔案
4) setFileSizeMax(long) // 上傳檔案單個最大值 fileupload内部通過抛出異常的形式處理, 處理檔案大小超出限制, 可以通過捕獲這個異常, 提示給使用者
5) setSizeMax(long) // 上傳檔案總量最大值
6) setHeaderEncoding(String) // 設定編碼格式
四、實作過程
1.導入jar包
2.編寫jsp
3.編寫servlet
//建立業務層對象
NewsService newsService = new NewsService();
InputStream in = null;
OutputStream out = null;
int id = 0;//頁面傳來的id值
//建立解析器工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//擷取解析器
ServletFileUpload upload = new ServletFileUpload(factory);
// 上傳表單是否為multipart/form-data類型
if(!upload.isMultipartContent(request)) {
return ;
}
//解析request的輸入流
try {
List parseRequest = upload.parseRequest(request);
//疊代list
for(FileItem f:parseRequest) {
if(f.isFormField()) {
//普通字段
id = Integer.parseInt(f.getFieldName());
String value = f.getString();
System.out.println("name"+"="+value);
}else {
//上傳檔案
//擷取上傳檔案名
String name = f.getName();
System.out.println("檔案名"+name);
name = name.substring(name.lastIndexOf("")+1);
System.out.println(name);
//擷取輸入流
in = f.getInputStream();
//擷取上傳檔案路徑
String savePath = "D:workspacedt91FileUpLoadTestDemoWebContentimages"+name;
//上傳檔案名若不存在, 則先建立
File path = new File(savePath);
if(!path.exists()) {
path.getParentFile().mkdir();
}
//擷取輸出流
out = new FileOutputStream(path);
int len = 0;
byte[] b = new byte[1024];
while((len = in.read(b)) > 0) {
out.write(b,0,len);
}
System.out.println("上傳成功");
//儲存到資料庫
int count = newsService.saveUrl(name, id);
if(count > 0 ) {
System.out.println("路徑儲存成功");
}else {
System.out.println("路徑儲存失敗");
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
System.out.println("上傳失敗");
e.printStackTrace();
}finally {
if(in != null) {
in.close();
}
if(out != null) {
out.close();
}
}