实现上传

method="post" enctype="multipart/form-data">

<%
request.setCharacterEncoding("UTF-8");

News news=new News();
news.setCreateDate(new Date());

boolean isMultipart=ServletFileUpload.isMultipartContent(request);
String realpath=request.getSession().getServletContext().getRealPath("upload/");
File getrealpath=new File(realpath);
if(!getrealpath.exists()){
getrealpath.mkdir();
}

if(isMultipart){
//创建工厂
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);

List<FileItem> list=upload.parseRequest(request);
Iterator<FileItem> iter=list.iterator();
while(iter.hasNext()){
FileItem fi=iter.next();
if(fi.isFormField()){
if(fi.getFieldName().equals("categoryId")){
news.setCategoryId(Integer.parseInt(fi.getString()));
}
if(fi.getFieldName().equals("title")){
news.setTitle(fi.getString("utf-8"));
}
if(fi.getFieldName().equals("newscontent")){
news.setContent(fi.getString("utf-8"));
}
if(fi.getFieldName().equals("author")){
news.setAuthor(fi.getString("utf-8"));
}
if(fi.getFieldName().equals("summary")){
news.setSummary(fi.getString("utf-8"));
}
}else{
String getname=fi.getName();
File file=new File(getname);
if(file.getName()!=null&&!file.getName().equals("")){
File realfile=new File(realpath,file.getName());
fi.write(realfile);
news.setPicPath(realfile.getName());
}

}


}

}








if(newsService.addNews(news)){
%>
<jsp:forward page="newsDetailList.jsp"/>
<%
//request.getRequestDispatcher("newsDetailList.jsp").forward(request, response);
}
%>

posted @ 2017-06-02 06:20  m97i  阅读(118)  评论(0编辑  收藏  举报