之前有實現過使用struts2實現文件上傳的功能,直接使用框架來實現文件上傳的確很方便。但是容易讓人忽略其中的細節,今天先將最近使用common-fileupload 和 common-io 包來實現文件上傳的方法記錄下來,以供參考。
1. 首先導入jar包,common-fileupload 和 common-io
2. 編碼實現(如何在web.xml中配置action這裏省略):
public class Upload extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory dfi = new DiskFileItemFactory();
String path = "F:" + File.separator + "upload"; // 獲得上傳文件的存儲路徑
File file=new File(path);
if(!file.exists()){
file.mkdirs();
}
String fileName="";
dfi.setSizeThreshold(1024 * 1024); // 設置文件大小超過1024*1024就寫到disk上
dfi.setRepository(file); // 設置存儲的倉庫
ServletFileUpload sfu = new ServletFileUpload(dfi); // 實例化一個servletFileUpload對象
sfu.setHeaderEncoding("utf-8"); // 解決上傳文件亂碼問題
try {
List<FileItem> list = sfu.parseRequest(request);
HttpSession session = request.getSession(); // 取得session
for (FileItem item : list) { // 遍歷得到每個FileItem
String name = item.getFieldName(); // 取得表單文本框的名字
if (item.isFormField()) { // 如果上傳的這個文件只是一個表單字段,而不是一個文件
String value = item.getString(); // 取得文本框輸入的內容
session.setAttribute(name, value); // 存儲數據
}else {
// 如果上傳的是一個文件
// 取得上傳文件的名字,即上傳框中的內容名字
String value = item.getName();
// 因爲在opera瀏覽器中文件上傳item.geName()會得到具體路徑而不止是名字,所以需要從路徑中取出名字
// 取得文件路徑名字開始的位置
int start = value.lastIndexOf("\\");
// 得到文件名
fileName = value.substring(start + 1);
// 讀取文件的內容
item.write(new File(path, fileName));
// 存儲數據
session.setAttribute(name, fileName);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}