实现上传
Posted m97i
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现上传相关的知识,希望对你有一定的参考价值。
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);
}
%>
以上是关于实现上传的主要内容,如果未能解决你的问题,请参考以下文章