前台
JSP:
<button class="btn btn-danger" id="download_btn" th:text="#{DOWNLOAD_OQC_EXC_BTN_TAG}"></button>
JS:
//定义按钮
var domObj = {
button: {
$download_btn: $("#download_btn"),
},
};
//按钮逻辑
var btnFunc = {
download_func: function () {
var filePath = "E:/workspace_oem/oem-jn/src/main/resources/static/excelModel"
var fileName = "出货模板.xlsx";
if ($("#downForm").length > 0) {
$("#downForm").remove();
}
var str = '<form id="downForm" action="download.do" method="post">';
str = str + '<input type="hidden" name="filePath" id= "filePath" />';
str = str + '<input type="hidden" name="fileName" id= "fileName" />';
str = str + "</form>";
$(str).appendTo("body");
$("#filePath").val(filePath);
$("#fileName").val(fileName);
$("#downForm").submit();
}
};
var iniButtonAction = function () {
domObj.button.$download_btn.click(function () {
btnFunc.download_func();
});
};
//页面初始化后执行的方法
var initializationFunc = function () {
iniButtonAction();
};
//页面加载后执行
initializationFunc();
后台:
@Controller//使用Controller管理
public class ExcelController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private IRetBoxInfoRepository retBox;
@RequestMapping(value = "/download.do")
public void downloadModel(HttpServletRequest request, HttpServletResponse response, HttpSession session,String filePath,String fileName) throws IOException {
if (StringUtils.isEmpty(fileName)) {
fileName = "NameUndefined";
}
// String temp1 = File.separator;//路径分隔符("\\")
String url = filePath + "/" + fileName;
System.out.println("filedownload =" + url);
export(request, response, url, fileName);
}
public void export(HttpServletRequest request, HttpServletResponse response,String url,String fileName) throws IOException {
response.setContentType("application/octet-stream");
if (request.getHeader("user-agent").toLowerCase().indexOf("firefox") > -1) {
//火狐浏览器自己会对URL进行一次URL转码所以区别处理
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
} else {
response.setHeader("Content-Disposition", "attachment;filename="
+ URLEncoder.encode(fileName,"utf-8")); }
//新建文件输入输出流
OutputStream output = null;
FileInputStream fis = null;
try{
File f = new File(url);//新建File对象
output = response.getOutputStream();//新建文件输入输出流对象
fis = new FileInputStream(f);
byte[] b = new byte[(int)f.length()]; //设置每次写入缓存大小
//把输出流写入客户端
int i = 0;
while((i = fis.read(b)) > 0){
output.write(b, 0, i);
}
output.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
fis = null;
}
if(output != null)
{
output.close();
output = null;
}
}
}
}