zoukankan      html  css  js  c++  java
  • servlet文件上传

    jsp:

    servlet:

    /*
    *
    * 文件上传
    */
    public class UploadServlet extends HttpServlet {

    /**
    * Constructor of the object.
    */
    public UploadServlet() {
    super();
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {


    String url=request.getServletPath();
    if(url.contains("add"))
    {
    //上传路径
    String filePath = getServletContext().getRealPath("/")+"upload";
    //如果文件夹不存在 则创建这个文件夹
    File file = new File(filePath);
    if(!file.exists())
    {
    file.mkdir();
    }

    request.setCharacterEncoding("UTF-8");

    //初始化smartupload对象
    SmartUpload upload=new SmartUpload();
    upload.initialize(getServletConfig(), request,response);
    //设置上传文件大小
    upload.setMaxFileSize(1024*1024*2);
    //设置上传文件的格式
    upload.setAllowedFilesList("jpg,png,gif");
    try {
    //文件开始上传
    upload.upload();
    //对文件名字不做修改的上传
    //upload.save(filePath);

    // 如果要对文件进行重命名 使用saveAs()
    String ext = upload.getFiles().getFile(0).getFileExt() ; //取得文件的扩展名
    String picname=System.currentTimeMillis()+"";
    upload.getFiles().getFile(0).saveAs("/upload/"+picname+"."+ext) ;


    //获取表单中的文本框


    String name=upload.getRequest().getParameter("name");
    Connection con=Dbutil.getconnect();

    String insert="insert into product (name,pic) value(?,?)";
    PreparedStatement preparedStatement=con.prepareStatement(insert);

    preparedStatement.setString(1, name);
    preparedStatement.setString(2, picname+"."+ext);
    preparedStatement.execute();






    String select="select * from product";

    preparedStatement=con.prepareStatement(select);

    ResultSet r=preparedStatement.executeQuery();
    List<Product> list=new ArrayList();
    while(r.next())
    {
    Product product=new Product();
    product.setId(r.getInt("id"));
    product.setName(r.getString("name"));
    product.setPic(r.getString("pic"));
    list.add(product);
    }
    preparedStatement.close();
    Dbutil.realConnection(con);

    request.setAttribute("list", list);
    request.getRequestDispatcher("/jsp/list.jsp").forward(request, response);




    } catch (SmartUploadException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }


    }

  • 相关阅读:
    Swagger使用总结
    idear常用快捷键
    Liunx下安装MongoDB
    python面向对象的特点,类定义等,私有属性、公有属性、成员属性
    Python,subprocess模块(补充)
    对称加密和非对称加密概述
    Python关于导入模块的一些感想:
    Python学习第二阶段Day2,模块subprocess、 logging、re
    Python学习第二阶段Day2(json/pickle)、 shelve、xml、PyYAML、configparser、hashlib模块
    Python学习第二阶段Day2,模块time/datetime、random、os、sys、shutil
  • 原文地址:https://www.cnblogs.com/love1/p/7657489.html
Copyright © 2011-2022 走看看