下载--保存(下载)文件到本地(.doc .jpg)

    public ActionForward downloadxsxz(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
    {
        /**
         * 获得待导出文件路径和自定义下载文件名
         */
        String filepath = request.getParameter("filepath");//英文名。doc
        String _expfname = request.getParameter("expfname");//中文名
        String houzhui = request.getParameter("houzhui");//英文名  。doc  .img
        _expfname = ExportAction.decodeBase64(_expfname,"UTF-8");

        /**
         * 文件名为空则直接跳出执行
         */
        if (filepath == null || "".equals(filepath.trim()))
            return null;
        /**
         * 格式化文件名
         */
        filepath = "e:/test/";

        /**
         * 取得路径配置   判断是那种类型
         * XsxzBysPicPath
         * XsxzBysDocPath
         */
        
        String _folder = "";
        
        if(   "doc".equals(houzhui)){
            _folder = SISConfigFactory.getIetConfig().get(XsxzBysDocPath);
        }else if("img".equals(houzhui)){
            _folder = SISConfigFactory.getIetConfig().get(XsxzBysPicPath);
        }
        
        File _fld = new File(_folder);
        if (!_fld.exists())
            _fld.mkdir();

        File file = new File(_folder + filepath);
        /**
         * 当没有配置自定义下载的文件名时,取硬盘文件名
         */
        if (_expfname == null || "".equals(_expfname.trim()))
            _expfname = file.getName();

        try
        {
            /**
             * 输出文件
             */
            FileInputStream in = new FileInputStream(file);
            response.setContentType("application/x-msdownload");
            response.setContentLength(in.available());
            response.setHeader("Content-Disposition", "attachment;" + "filename="
                    + java.net.URLEncoder.encode( _expfname, "UTF-8").replaceAll("\\+", " "));
            OutputStream out = response.getOutputStream();
            byte[] bb = new byte[1024];
            int a = -1;
            while ((a = in.read(bb)) != -1)
            {
                out.write(bb, 0, a);
            }
            out.close();
            in.close();
            /**
             * 输出结束后,删除硬盘上文件
             */
//            if (org.apache.commons.lang.StringUtils.isBlank(_deleteflag) && file.exists())
//                file.delete();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

 

posted on 2013-02-28 23:32  BIGBIRD大鸟  阅读(325)  评论(0编辑  收藏  举报