private static final long serialVersionUID = 1L;
private File uploadPath;
private File tempPath;
@Override
public void init() throws ServletException {
uploadPath = new File(getServletContext().getRealPath("upload"));
System.out.println("uploadPath=====" + uploadPath);
// 如果目錄不存在
if (!uploadPath.exists()) {
// 創建目錄
uploadPath.mkdir();
}
// 臨時目錄
// File tempFile = new File(item.getName())構造臨時對象
tempPath = new File(getServletContext().getRealPath("temp"));
if (!tempPath.exists()) {
tempPath.mkdir();
}
// 如果不顯示調用父類方法,就不會有itemManager實例,因此會造成空指針
super.init();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@SuppressWarnings("deprecation")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 從item_upload.jsp中拿取數據,因為上傳頁的編碼格式跟壹般的不同,使用的是enctype="multipart/form-data"
// form提交采用multipart/form-data,無法采用req.getParameter()取得數據
// String itemNo = req.getParameter("itemNo");
// System.out.println("itemNo======" + itemNo);
/******************************** 使用 FileUpload 組件解析表單 ********************/
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
factory.setRepository(tempPath);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
// maximum size before a FileUploadException will be thrown
upload.setSizeMax(1000000 * 20);
try {
List<?> items = upload.parseRequest(request);
String data = "";
int i = 0;
String itemNo = "";
String fileName = "";
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
i++;
data = item.getString();
if ("itemNo".equals(item.getFieldName())) {
itemNo = item.getString();
}
}
// 是否為input="type"輸入域
else if (!item.isFormField()) {
// 上傳文件的名稱和完整路徑
fileName = item.getName();
System.out.println("filename==="+fileName);
long size = item.getSize();
// 判斷是否選擇了文件
if ((fileName == null || fileName.equals("")) && size == 0) {
continue;
}else{
fileName = System.currentTimeMillis() + ".jpg";
}
// 截取字符串 如:C:\WINDOWS\Debug\PASSWD.LOG
fileName = fileName.substring(
fileName.lastIndexOf("\\") + 1, fileName.length());
// 保存文件在服務器的物理磁盤中:第壹個參數是:完整路徑(不包括文件名)第二個參數是:文件名稱
// item.write(file);
// 修改文件名和物料名壹致,且強行修改了文件擴展名為gif
// item.write(new File(uploadPath, itemNo + ".gif"));
// 將文件保存到目錄下,不修改文件名
item.write(new File(uploadPath, fileName));
}
}
response.sendRedirect(request.getContextPath() + "/people_require.html");
} catch (Exception e) {
e.printStackTrace();
}
}
}