• JSP页面实现上传下载


    本文使用的是smartupload工具实现文件的上传下载:

    工具:

    1、Eclipse

    2、jspsmart.jar(百度搜索jspsmartupload.jar下载)

    JSP页面:

     1 <%--上传 --%>
     2 <form action="upload" method="post" enctype="multipart/form-data">
     3 <input type="file" name="file">
     4 <input type="submit" value="上传">
     5 </form>
     6 
     7 
     8 <%--下载 --%>
     9 <a href="down?file=A.jpg">下载</a>
    10 <form action="down" method="post">
    11 <input type="hidden" name="file" value="B.jpg">
    12 <input type="submit" value="下载">
    13 </form>

    Servlet上传处理页面:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //设置字符集(可以通过Filter设置)
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            //获取一个SmartUpload对象
            SmartUpload upload=new SmartUpload();
            //初始化
            ServletConfig config=this.getServletConfig();
            upload.initialize(config, request, response);
            try {
                //上传文件
                upload.upload();
                //获取上传的文件对象
                File file=upload.getFiles().getFile(0);
                //指定保存文件的路径
                java.io.File newfile=new java.io.File(this.getServletContext().getRealPath("/")+"image");
                if(!newfile.exists())
                {
                    newfile.mkdirs();
                }
                //保存文件
                file.saveAs(newfile+"/"+file.getFileName(), file.SAVEAS_PHYSICAL);
                response.getWriter().println("上传成功");
                System.out.println(newfile+"/"+file.getFileName());
            } catch (SmartUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    Servlet下载处理页面:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {              
            //从JSP页面获取到用户需要下载的文件名
            String file=request.getParameter("file");
            //获取一个SmartUpload对象
            SmartUpload download=new SmartUpload();
            //初始化
            ServletConfig config=this.getServletConfig();
            download.initialize(config, request, response);
            //禁止浏览器根据后缀名自动打开文件
            download.setContentDisposition(null);
            try {
            //指定下载地址    
    download.downloadFile(this.getServletContext().getRealPath("/")+"image/"+file);
    } catch (SmartUploadException e) { e.printStackTrace(); } }
  • 相关阅读:
    ksframework的xlua版本
    unity摄像机脚本
    代码重构:用工厂+策略模式优化过多的if else代码块
    在Unity中创建攻击Slot系统
    Unity运用GPU代替CPU处理和计算简单测试
    程序员工具集
    Unity开发-你必须知道的优化建议
    unity向量计算
    ClassFoo-IT知识花园
    BZOJ 3446: [Usaco2014 Feb]Cow Decathlon( 状压dp )
  • 原文地址:https://www.cnblogs.com/darren0415/p/6023645.html
Copyright © 2020-2023  润新知