JSP點(diǎn)擊鏈接后下載文件功能

字號(hào):


    /** *//**
    * 實(shí)現(xiàn)文件另存功能
    *
    * @param text
    * 文件內(nèi)容
    * @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() + "https://upload.ynpxrz.com/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;
    }