1. 程式人生 > >實現上傳

實現上傳

next() tail sse file session part load tpi method

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

實現上傳