本文使用的是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();
        }
    }

 

参考文章:http://blog.ncmem.com/wordpress/2023/09/14/jsp页面实现上传下载/