欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JSP文件下载(不使用jar包)

程序员文章站 2022-04-15 13:29:12
  java代码: public class download extends httpservlet { public download() { su...

 

java代码:

public class download extends httpservlet {

    public download() {
        super();
    }

    public void destroy() {
        super.destroy(); // just puts destroy string in log
        // put your code here
    }

    public void doget(httpservletrequest request, httpservletresponse response)
            throws servletexception, ioexception {

        this.dopost(request, response);
    }

    public void dopost(httpservletrequest request, httpservletresponse response)
            throws servletexception, ioexception {
        string path = d:/upload/哈哈哈.txt;
        try {
            // path是指欲下载的文件的路径。
            file file = new file(path);
            // 取得文件名。
            string filename = file.getname();
            // 取得文件的后缀名。
            string ext = filename.substring(filename.lastindexof(.) + 1).touppercase();

            // 以流的形式下载文件。
            inputstream fis = new bufferedinputstream(new fileinputstream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的header
            response.addheader(content-disposition, attachment;filename= + new string(filename.getbytes(gb2312),iso8859-1));
            response.addheader(content-length,  + file.length());
            outputstream toclient = new bufferedoutputstream(response.getoutputstream());
            response.setcontenttype(application/octet-stream);
            toclient.write(buffer);
            toclient.flush();
            toclient.close();
        } catch (ioexception ex) {
            ex.printstacktrace();
        }
    }

    public void init() throws servletexception {
        // put your code here
    }

}

JSP文件下载(不使用jar包)