level 1
otected void add(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter(); // 设置保存上传文件的目录
String uploadDir = getServletContext().getRealPath("/upload");
// System.out.println(uploadDir);
if (uploadDir == null) {
out.println("无法访问存储目录");
return;
} File fUploadDir = new File(uploadDir); if (!fUploadDir.exists()) {
if (!fUploadDir.mkdir()) {
out.println("无法创建存储目录");
return;
}
} if (!DiskFileUpload.isMultipartContent(request)) {
out.println("只能处理multipart/form-data类型的数据");
return;
} DiskFileUpload fu = new DiskFileUpload();
// 最多上传 200M 数据
fu.setSizeMax(1024 * 1024 * 200);
// 超过 1M 的字段数据采用临时文件缓存
fu.setSizeThreshold(1024 * 1024);
// 采用默认的临时文件存储位置
// fu.setRepositoryPath(...);
// 设置上传的普通字段的名称和文件字段名所采用的字符集编码
fu.setHeaderEncoding("utf-8"); // 得到所有表单字段对象的**
List fileItems = null;
try {
fileItems = fu.parseRequest(request);
} catch (FileUploadException e) {
out.println("解析数据时出现如下问题");
e.printStackTrace(out);
return;
} // 处理每个表单字段
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (fi.isFormField()) {
String content = fi.getString("utf-8");
String filedName = fi.getFieldName();
request.setAttribute(filedName, content);
} else {
try {
String pathSrc = fi.getName();
/**
* 如果用户没有在form表单的文件字段中选择任何文件, 那么忽略对该字段项的处理
*/
if (pathSrc.trim().equals("")) {
continue;
}
int start = pathSrc.lastIndexOf('\\');
String fileName = pathSrc.substring(start + 1);
File pathDest = new File(uploadDir, fileName); fi.write(pathDest);
String fieldName = fi.getFieldName();
request.setAttribute(fieldName, fileName);
} catch (Exception e) {
out.println("存储文件时出现如下问题");
e.printStackTrace(out);
return;
} finally {
fi.delete();
}
}
}
String title = (String) request.getAttribute("title");
Object type1 = request.getAttribute("type");
int type = Integer.parseInt((String) type1);
String titleImage = (String) request.getAttribute("titleImage");
String content = (String) request.getAttribute("content");
newsBean nb = new newsBean();
nb.setTitle(title);
nb.setType(type);
titleImage = uploadDir + "\\" + titleImage;
nb.setTitleImage(titleImage);
nb.setContent(content);
NewsService nse = new NewsService();
nse.addNews(nb);
LogDao logg = new LogDao();
String message = "";
message = "添加新闻成功!";
logg.greatlog(request, message);
response.sendRedirect("NewsServlet?action=all");
}
2011年12月10日 02点12分