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();
}
}
上一篇: java数据结构和算法09(哈希表)
下一篇: Java添加、提取、替换和删除PDF图片