JSP教程:点击链接后下载文件(右键另存)功能

    文章来源:万象互联 更新时间:2011-8-18 14:30:34
分享:

万象互联网络资讯网提示:/** *//** * 实现文件另存功能 * * @param text * 文件内容 * @param fileName * 文件名称 * @return */ protected String renderFile(String text, String fileName) throws IOException { response.addHeader(Content-Disposition, attachment; filename= + fileName

/** *//**
     * 实现文件另存功能
     * 
     * @param text
     *            文件内容
     * @param fileName
     *            文件名称
     * @return
     */
    protected String renderFile(String text, String fileName)
            throws IOException
    {
        response.addHeader("Content-Disposition", "attachment; filename="
                + fileName);
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("GB2312");
        response.getWriter().write(text);
        response.flushBuffer();
        response.getWriter().close();
        return null;
    }

 

下载的action:

/** *//**
     * 提供下载的方法
     * @return
     */
    public String down()
    {
        String dir = getFullPath() + "/upload/file/";
        try
        {
            if (!FileUtils.exists(dir))
            {
                new File(dir).mkdirs();
            }
            Random r = new Random(System.currentTimeMillis());
            Integer randomInt = r.nextInt();
            this.renderFile("test content:" + randomInt,randomInt + ".txt");
        }
        catch (IOException e)
        {
            e.printStackTrace();
            this.renderText(e.getMessage());
        }
        return null;
    }

 

页面链接调用:

<a href="${ctx}/va/va!down.do" >下载</a>

版权说明:本站原创文章,由万象互联SEO优化发表.
本文地址:https://www.hulian.top/zixun/post/4129.html
在线咨询
  • 在线时间
  • 8:00-21:00