首页 > 代码库 > 实现上传

实现上传

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);
}
%>

实现上传