//这是html中的一部分 下载按钮
<button type="button" id="btn" class="layui-btn">下载
</button>
//以下是js代码 点击按钮的时候调用
$("#btn").on('click',function () {
postDownLoadFile({
url : base_url + "/file/download", //这里写后台请求的url
data :{
params1:params1, //这里可以选择自己要传递的参数
params2:params2
},
method : 'post'
});
});
//后台返回成功后回填的数据
var postDownLoadFile = function(options) {
var config = $.extend(true, {
method : 'post'
}, options);
var $iframe = $('<iframe id="down-file-iframe" />');
var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
$form.attr('action', config.url);
for ( var key in config.data) {
$form
.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
}
$iframe.append($form);
$(document.body).append($iframe);
$form[0].submit();
$iframe.remove();
}
以下是后台代码
@RestController
@RequestMapping("/file")
public class DownloadController1 {
//业务上需要的参数可以如param1 传递
@RequestMapping(value = "/download")
public Map<String, Object> download(HttpServletRequest request, HttpServletResponse response,String param1,String param2 ) throws Exception {
String realName = "第一节(2).zip"; //文件在浏览器的显示位置
String downLoadPath = ""; //这个参数表示文件在服务器的存储路径
String contentType = "application/octet-stream";
try {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
long fileLength = new File(downLoadPath).length();
response.setContentType(contentType);
response.setHeader("Content-disposition",
"attachment; filename=" + new String(realName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
} catch (Exception e) {
return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "", "");
}
}
}
后台成功返回后,浏览器如下图显示,点击下载就可以了
前端部分参考的这位大兄弟,在此感谢。
https://blog.youkuaiyun.com/xuxie13/article/details/82145099