后台通过读取流的形式,实现下载功能

jsp前台:jsp代码内潜入隐藏的form
 
                 <div class="accordion">
				<map name="FPMap0">
					<area  href="#" οnclick="downloads();"  shape="rect" coords="7, 198, 181, 250">
				</map>
				<ul style="display: inline-block;">
					<img src="${ctx}/images/lc.gif"  usemap="#FPMap0"/>
				</ul>
			</div>
			<span style="color:#ff0000;"><form id="uploadForm" action="${ctx}/upload/downloadFile" method="post">
				<input type="hidden" name="fileName" id="fileName" />
			</form></span>

 
提交form的js 方法:
<span style="white-space:pre">	</span><pre name="code" class="javascript">function downloads() {
		var fileName="密码重置受理表.doc";
		$("#fileName").val(fileName);
		$("#uploadForm").submit();
	}

 
controllor 层方法实现 
@RequestMapping("/downloadFile")
    public String download(String fileName, HttpServletResponse response) {
        try {
            String path = getRequest().getSession().getServletContext().getRealPath("/") + "docs/" + fileName;
            logger.info("#downloadFile#path=" + path);
            File file = new File(path);
            response.reset();
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.addHeader("Content-Length", "" + file.length());
            String agent = getRequest().getHeader("USER-AGENT");
            /*if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")) {// ie
                fileName = java.net.URLEncoder.encode(fileName, "UTF8");
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            }*/
            fileName =  new String(fileName.getBytes("gbk"), "iso-8859-1");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            InputStream inputStream = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }

            // 这里主要关闭。
            os.close();

            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 返回值要注意,要不然就出现下面这句错误!
        // java+getOutputStream() has already been called for this response
        return null;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值