//存放文件上傳的路徑
private String dirPath = "D:/upload";
//創(chuàng)建一個上傳文件的方法,用apache提供的上傳組件實現(xiàn)(2個相關(guān)聯(lián)的包)public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception{//創(chuàng)建文件上傳工廠對象FileItemFactory factory = new DiskFileItemFactory();//創(chuàng)建文件上傳的核心類ServletFileUpload upload = new ServletFileUpload(factory);//設(shè)置單個文件允許的最大大小upload.setFileSizeMax(10*1024*1024);//10M//設(shè)置表單中所有文件的最大容量,設(shè)為30Mupload.setSizeMax(30*1024*1024);//30M//設(shè)置文件名的編碼方式,可以不用設(shè)置//相當(dāng)于request.setCharacterEncoding("utf8");upload.setHeaderEncoding("utf8");//判斷是否文件上傳表單if (upload.isMultipartContent(request)) {//把請求數(shù)據(jù)轉(zhuǎn)換為FileItem對象,將所有FileItem對象放入集合中Listlist = upload.parseRequest(request);
for (FileItem item : list) {
//判斷是否是普通文本數(shù)據(jù) form的text等
if (item.isFormField()) {
//得到表單元素的名稱和值(key、value)
System.out.println(item.getFieldName());//key
item.getString();//value
//得到表參數(shù)中對應(yīng)的數(shù)據(jù)
System.out.println(item.getString("utf8"));
}else {//說明是文件
String name = item.getName();
String id = UUID.randomUUID().toString().replace("-", "");//去掉uuid的“-”
if (name==null||name.isEmpty()) {
continue;
}
//生成新的文件名
name = id+"-"+name;
//如果上傳目錄不存在,創(chuàng)建
File f = new File(dirPath);
if (!f.exists()) {
f.mkdirs();
}
//創(chuàng)建目標(biāo)文件(兩者組合一個路徑)
File file = new File(dirPath,name);
//上傳文件
item.write(file);
//刪除完上傳過程中產(chǎn)生的臨時文件
item.delete();
}
}
}
}


注:******
