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

java 下载文件

程序员文章站 2022-04-09 09:24:00
...

HTML页面代码

function down(index){
	var rowdata=_result[index];
	var hqId=rowdata.hqId;
	var url = "../rest/hisQueTemp/down?hqId="+hqId;  //mybatis+spring  
    url = encodeURI(url);
    location.href = url; 
}

后台代码

/**
     * 下载
     * @return
     */
    @RequestMapping(value = "/down")//POST
    @ResponseBody
    public void downTXT(String hqId, Model model, HttpServletRequest request, HttpServletResponse response)  throws IOException{
		TAicsHistoryQuestionTemp hq = tAicsHistoryQuestionTempMapper.selectByPrimaryKey(Long.parseLong(hqId));
		String str = hq.getHqPath();
		String strName = str.split("__")[1];
		String fileType = str.substring(str.lastIndexOf(".") + 1);
		System.out.println(str);
		File f = new File(str);
		
		// 设置response参数,可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		try { 
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((strName).getBytes(), "iso-8859-1"));// 下载文件的名称 
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(f));
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}
相关标签: 下载