点击a标签实现txt文件另存的效果

亲测成功,使用servlet实现的,核心代码:

前台代码:

function downModel(filePath){
var formFile=$("<form>");
formFile.append("<input name='fileName' style='display:none;' value='batchInsertUsersDemo.txt'/>");
formFile.attr("action","downFileByPath").attr("method","post").attr("display","none");
$("body").append(formFile);
formFile.submit();
}

后台代码:

String fileName=req.getParameter("fileName");
String filePath=DownFileByPathServlet.class.getResource("//").toString()+fileName;// 该java文件所在电脑的位置
FileInputStream inputStream=new FileInputStream(filePath.substring(5));
OutputStream outputStream=resp.getOutputStream();
int i = inputStream.available();
byte[] content = new byte[i];
inputStream.read(content);
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment;filename="+fileName);
try {
outputStream.write(content);
} catch (Exception e) {
e.printStackTrace();
}finally{
outputStream.flush();
inputStream.close();
outputStream.close();
}

 

posted @ 2017-06-03 17:04  狂奔的程序猿  阅读(810)  评论(0)    收藏  举报