浏览器客户端从服务器下载文件到本地

时间:2022-10-19 17:12:06

技术背景:Java技术框架SSM(Spring+Struts+Mybatis)

1.一种常用的经过服务器后端的安全方式

前端jsp:

按钮:

<button type="button" class="btn highlight" onclick="getTemplate()">模版下载</button>

<script>

function getTemplate(){
 window.open('${web.context.path}/sensitiveWords/getTemplateSensitiveWordsAction'); 

}

</script>


或也可以直接用a标签链接代替
<a href="${web.context.path}/sensitiveWords/getTemplateSensitiveWordsAction">下载敏感词模版</a>


后端SensitiveWordsAction.java

public String getTemplate(){
log.info("===========SensitiveWordsAction.getTemplate()  start ===========");
queryJson = new HashMap<String, Object>();
try {
//从配置文件里读取
String sensitiveWordsServerUrl = SysConfig.getSysParam("sw_server_url");
//sw_server_url=http://101.123.50.110:8080/usr/test/sws.xlsx
if(StringUtils.isBlank(sensitiveWordsServerUrl)){
queryJson.put("ret", "1");
queryJson.put("retInfo", "敏感词库模版不存在!");
return JSON_RESULT;
}

HttpServletResponse response = ServletActionContext.getResponse();
response.sendRedirect(sensitiveWordsServerUrl );


queryJson.put("ret", "0");
queryJson.put("retInfo", "success");
} catch (Exception e) {
//内部程序错则返回
queryJson.put("ret", "1");
queryJson.put("retInfo", "内部程序错");
log.error("下载敏感词模版到客户端出错", e);
}
return JSON_RESULT;
}


红色两行是最关键的,用response的转发


2.一种直接从服务器硬盘下的不安全方式:

a标签链接:

<a href="http://101.123.110.159:8080/usr/test/sws.xlsx">点我下载</a>

或用按钮

<input type="button" value="从服务器下载" onclick="d()">

<script>

function d(){

window.open('http://101.123.110.159:8080/usr/test/sws.xlsx');

}

</script>