本文主要處理文件上傳后,在servlet中獲取并保存。
html中的代碼
<form enctype="multipart/form-data" action="此處填寫處理的servlet的url" method="post">
<input type="text" name="name"/>
...
<input type="file" name="uploadFile"/>
<input type="submit" value="提交"/>
</form>
servlet中的代碼
/*
* 兩件事: 1. 上傳圖片到服務(wù)器中的指定位置
*
* 2. 封裝對象
*/
// 1. 創(chuàng)建一個(gè)用生產(chǎn)FileItem(表單中的每一項(xiàng))的工廠
FileItemFactory factory = new DiskFileItemFactory();
// 創(chuàng)建文件上傳組件的解析對象
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 通過upload.parseRequest拿到表單中的每一項(xiàng)
List<FileItem> items = upload.parseRequest(request);
// 手動創(chuàng)建一個(gè)Map對象,用于之后轉(zhuǎn)化為bean
Map<String, String> dataMap = new HashMap<String, String>();
// 遍歷表單項(xiàng),找到文件,使用isFormField()方法,判斷是否是普通的表單項(xiàng)
for (FileItem item : items) {
// 普通表單項(xiàng)
if (item.isFormField()) {
String key = item.getFieldName();//獲取input中name值
String value = item.getString("UTF-8");//獲取input中value值
// 把獲取到的數(shù)據(jù)保存到map中
dataMap.put(key, value);
}
// 文件
else {
/*
* 1. 獲取文件名稱 這個(gè)文件名稱,不能直接使用,因?yàn)榭赡艽嬖谕膱D片
*
* 這個(gè)不需要下載圖片,因此文件名稱可以不要
*/
String fileName = item.getName();
// 獲取文件后綴名 1.jpg,先拿到最后一個(gè)點(diǎn)的位置
int index = fileName.lastIndexOf(".");
// 拿到的是“.jpg”
fileName = fileName.substring(index);
// 為文件重命名dsagdasgdsadgasd
String UUID = UUIDUtils.getUUID();
// 文件的保存到服務(wù)器的名稱
fileName = UUID + fileName;
// 指定圖片在服務(wù)器中保存的路徑
String savePath = "/upload";
// 目錄分離(目錄打散),保存到服務(wù)器中的最終的目錄為“/upload/2/3”
String dirs = DirUtils.getDir(fileName);
// 獲取服務(wù)器的真實(shí)路徑"
String realPath = request.getServletContext().getRealPath(
"");
// 判斷保存路徑是否存在,需要使用File類
String filePath = realPath + savePath + dirs;
System.out.println(filePath);
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
file = new File(file, fileName);
// 將文件保存到服務(wù)器中指定的位置
item.write(file);
// 保存商品的圖片路徑
dataMap.put("imgurl", savePath + dirs + "/" + fileName);
}
}
// 通過封裝好的Map對象,構(gòu)造bean對象
Good g = new Good();
BeanUtils.populate(g, dataMap);
// 調(diào)用service處理對象
GoodService service = new GoodServiceImpl();
service.addGood(g);
} catch (Exception e) {
e.printStackTrace();
}
工具類
UUIDUtils
/**
* 防止文件名重復(fù)UUID重寫文件名的方法
*/
public class UUIDUtils {
public static String getUUID() {
return UUID.randomUUID().toString().replace("-", "");
}
}
DirUtils
/**
* 根據(jù)文件名目錄打散工具類
*/
public class DirUtils {
public static String getDir(String name) {
if (name != null) {
int code = name.hashCode();
return "/" + (code & 15) + "/" + (code >>> 4 & 15);
}
return null;
}
}