• 基本完成了!!


    servlet的一些代码:(代码太多就不一一列举出来了)

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");//设置请求的编码
    resp.setContentType("text/html;charaset=utf-8");//设置响应的编码

    DiskFileItemFactory factory=new DiskFileItemFactory(45*1024,new File("d:/demo/temp"));//创建工厂//设置缓存大小
    ServletFileUpload sfu=new ServletFileUpload(factory);//创建解析器
    sfu.setFileSizeMax(45*1024);//设置文件单个大小45kb
    try {
    List<FileItem> fileItemList=sfu.parseRequest(req);//用解析器解析request对象
    Map<String, Object> map=new HashMap<String, Object>();//创建map用来接受book中的对应的值
    for(FileItem fileItem:fileItemList){
    if(fileItem.isFormField()){//如果输出的是文件的话
    map.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));//得到所定义的键和值
    }
    }
    Book book=CommonUtils.toBean(map, Book.class);//封装到book中
    book.setBid(CommonUtils.uuid());//为book制定bid
    Category category=CommonUtils.toBean(map, Category.class);//封装到category对象中
    book.setCategory(category);//设置到book对象中



    String savepath=this.getServletContext().getRealPath("/book_img");//得到有盘符的保存的路径
    String filenameString=CommonUtils.uuid()+"_"+fileItemList.get(1).getName();//得到第二个图片文件的名字

    //拓展名校验
    if(!filenameString.toLowerCase().endsWith("jpg")){
    req.setAttribute("msg", "你上传的不是以jpg结尾的图片");
    req.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(req, resp);//转发到添加的页面下
    return ;
    }


    File destionFile=new File(savepath,filenameString);//创建目标文件的对象

    fileItemList.get(1).write(destionFile);//写入上传的图片文件
    book.setImage("book_img/"+filenameString);//保存当前的book的image图片
    bookService.add(book);//保存当前上传之后的图书

    //图片校验
    Image image =new ImageIcon(destionFile.getAbsolutePath()).getImage();
    if(image.getWidth(null)>200||image.getHeight(null)>200){
    destionFile.delete();//删除图片
    req.setAttribute("msg", "你上传的图片尺度过大!");
    req.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(req, resp);//转发到添加的页面下
    return ;
    }

    req.getRequestDispatcher("/admin/AdiminBookServlet?method=findAll").forward(req, resp);//转发到查看所有图书的界面上面去
    } catch (Exception e) {
    if(e instanceof FileUploadBase.FileSizeLimitExceededException){
    req.setAttribute("msg", "你上传的文件大小,大于了45kb,所以你传不上!!!");
    req.getRequestDispatcher("/adminjsps/admin/book/add.jsp").forward(req, resp);//转发到添加的页面下
    }
    }
    }

  • 相关阅读:
    转:Windows 7下安装CentOS双系统
    STL学习总结之<迭代器>
    转:linux静态库与动态库
    指向类成员和成员函数的指针
    STL学习总结之<仿函数>
    转:Linux Crontab 定时任务 命令详解
    转: 解决 Redhat 出现”This system is not registered with RHN”更新
    IOS 判断设备屏幕尺寸、分辨率
    IOS 文件管理共通函数整理
    IOS 编译ffmpeg For SDK6.1,模拟器、armv7、armv7s均可使用
  • 原文地址:https://www.cnblogs.com/csnd/p/16675716.html
Copyright © 2020-2023  润新知