//這是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.csdn.net/xuxie13/article/details/82145099