jsp上传文件的操作过程

导入apache的commons-fileupload包和commons-io包

如果要上传数据库的话还需要导入对应的数据库jar包

jsp处理页编写

request.setCharacterEncoding("UTF-8");//设置中文字符集格式

FileItemFactory fif=new DiskFileItemFactory();//创建fileitemfactory对象

ServletFileUpload sfu=new ServletFileUpload(fif);//创建Servlet文件上传对象,参数列表:FileItemFactory对象

List<FileItem> list=sfu.parseRequest(request);//用Servlet文件上传对象处理请,获取文件项对象

FileItem fi=list.get(4);//获取文件域的位置
String fileName=fi.getName();//获取文件名
String fristName=System.currentTimeMillis()+"";//文件名不重复操作
String lastName=fileName.substring(fileName.lastIndexOf("."));//获取文件后缀
String path=application.getRealPath("upload/");//设置文件上传路径
File file=new File(path+fristName+lastName);//创建文件实例
fi.write(file);//将文件上传
// 上传文件
//设置要上传至数据库对象的取值
NewsInfoService nis=new NewInfoServiceImpl();
newinfo nf=new newinfo();
nf.setN_title(list.get(0).getString());
nf.setN_author(list.get(2).getString());
nf.setN_content(list.get(3).getString());
nf.setN_type(Integer.parseInt(list.get(1).getString()));
nf.setN_pic(fristName+lastName);
nis.addNewTypeService(nf);
//设置要上传至数据库对象的取值
原文地址:https://www.cnblogs.com/deemohans/p/12009289.html