使用到得技术:SmartUpload
需要的jar文件:smartupload.jar
需要的Biz:添加图书的biz
一:首先需要在form表单中,将提交方式更改为post,并且添加enctype的属性 multipart/form-data,并且在file文本域里面一定要添加 name属性
二:自己编写生成图片名子的方法(util)
三:在servlet中 添加如下几行(固定)
//1.实例化SmartUpload对象 //2.初始化上传操作initialize //3.上传准备
获取操作对象
保存对象名称信息
获取服务器目录,并保存req.getServletContext().getRealPath(“存放地址”+存放对象名称信息)
//保存文件
获取本地项目路径信息(绝对路径)
从服务器复制文件到项目地址:使用FileUtils.copyFile的工具类
//smartUpload对象来重新获取request对象
处理业务参数
private ServletConfig config;
SmartUpload smartUpload = new SmartUpload(); smartUpload.setCharset("UTF-8"); smartUpload.initialize(config, req, response); smartUpload.upload();
File file = smartUpload.getFiles().getFile(0); //保存图书片信息 String newFileName = IDUtil.getNewFileName(file.getFileName()); //req.getRealPath("/")获取的是服务器中该项目的根目录 String newfile = req.getServletContext().getRealPath("/booksimages/"+newFileName); file.saveAs(newfile); //把服务器的文件复制到本地项目中 String localPath="D:/lxsls/jyxy_web"+newFileName; //可以使用文件流复制文件,也可以使用工具类复制文件 FileUtils.copyFile(new java.io.File(newfile), new java.io.File(localPath)); //处理添加图书类型的请求 //1创建业务对象 因为表单使用了smartupload对象上传,默认的request已经不能获取表单的中参数,必须使用 //smartUpload对象来重新获取request对象 Request request = smartUpload.getRequest(); BookInfoBiz bookBiz = new BookInfoBiz(); //2处理业务参数(自己添加,内容,价格,数量,类型,简介等参数) String bname = request.getParameter("bname") ; String bprice = request.getParameter("bprice") ; String bnum = request.getParameter("bnum") ; String bcontent = request.getParameter("bcontent") ; String typeId = request.getParameter("typeId") ; BookInfo info = new BookInfo(); info.setBname(bname); info.setBcontent(bcontent) ; info.setBimage(newFileName) ; info.setBnumber(Integer.parseInt(bnum)) ; info.setBprice(Integer.parseInt(bprice)); info.setTypeid(Integer.parseInt(typeId)) ;
//处理小图片的信息 String[] imgs = request.getParameterValues("imgs"); //缩略图 //3调用业务方法 bookBiz.addBook(info,imgs) ; //重定向? 转发? response.sendRedirect(req.getContextPath()+"/admin/main.jsp"); |
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
this.config = config;
super.init(config);
}