-
首先form表单属性要设置带有文件上传属性的
enctype="multipart/form-data"
-
带有此条属性的表单在servlet里的getParamter就会获取不到相应的name==value值。所以在带有文件上传功能的表单中,要判断属性的name值是否为文件上传属性。
具体代码解释如下:
只看Post方法即可。
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String method = req.getParameter("method");
switch (method) {
case "message":
try {
message(req, resp);
} catch (ParseException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
private void message(HttpServletRequest req, HttpServletResponse resp)
throws ParseException, IOException {
// 创建New对象
News news = new News();
System.out.println("临时文件的存放位置:--->"
+ System.getProperty("java.io.tmpdir"));
// 创建Factory对象 可以设置缓冲区大小 以及存储位置
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 判断是否是文件上传类型
boolean flag = upload.isMultipartContent(req);
// 如果是文件上传类型
if (flag) {
try {
// 获取所有的表单元素
List<FileItem> items = upload.parseRequest(req);
Iterator<FileItem> its = items.iterator();
// 遍历表单元素
while (its.hasNext()) {
// 获取遍历器
FileItem item = its.next();
// 判断表单是什么元素
if (item.isFormField()) {
// 若是普通元素
String fieldName = item.getFieldName();
switch (fieldName) {
case "title":
news.setTitle(item.getString("UTF-8"));
break;
case "time":
news.setCreateTime(new SimpleDateFormat("dd/MM/yy")
.parse(item.getString("UTF-8")));
break;
case "content":
news.setContent(item.getString("UTF-8"));
break;
}
} else {
// 若是文件元素
String uploadPath = req.getSession()
.getServletContext().getRealPath("upload/"+System.currentTimeMillis()+"");
// 创建upload文件夹
File file = new File(uploadPath);
if (!file.exists()) {
file.mkdirs();
}
// 获取上传文件的名称
String fileName = item.getName();
System.out.println(fileName);
if (!"".equals(fileName) && null != fileName) {
File saveFile = new File(uploadPath, fileName);
item.write(saveFile);
news.setImg(uploadPath + "\\" + fileName);
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
boolean add = newsSer.add(news);
if (add) {
resp.setContentType("text/html;charset=GBK");
PrintWriter out = resp.getWriter();
out.print("<meta http-equiv='Content-Type' content='text/html; charset=GBK'>");
out.print("<script>");
out.print("alert('新闻添加成功!');");
out.print("window.location.href='index.jsp'");
out.print("</script>");
out.flush();
out.close();
} else {
resp.setContentType("text/html;charset=GBK");
PrintWriter out = resp.getWriter();
out.print("<meta http-equiv='Content-Type' content='text/html; charset=GBK'>");
out.print("<script>");
out.print("alert('新闻添加失败,请重新添加!');");
out.print("window.location.href='form_upload.jsp'");
out.print("</script>");
out.flush();
out.close();
}
}
}