前台
var form=$("<form>");//定义一个form表单
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");
form.attr("action",contextPath + "/exportFile.do?file_name=" + encodeURI(encodeURI("赛程安排表.xls")) + "&oldName=" + encodeURI(encodeURI("赛程安排表.xls")));
var input1=$("<input>");
input1.attr("type","hidden");
input1.attr("name","exportFile");
input1.attr("value",(new Date()).getMilliseconds());
form.append(input1);
$("#uploadfile_div").append(form);//将表单放置在web中
form.submit();//表单提交
在Spring 后台
public void exportFile(String file_name, String oldName, HttpSession session, HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
String fileName = java.net.URLDecoder.decode(file_name,"UTF8");
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + new String(oldName.getBytes("GB2312"), "ISO_8859_1"));
String realPath = request.getSession().getServletContext().getRealPath("/uploadFile");
realPath = realPath.replace("\\", "/");
try {
File file=new File(realPath+"/"+fileName);
System.out.println(file.getAbsolutePath());
InputStream inputStream=new FileInputStream(file);
OutputStream os=response.getOutputStream();
byte[] b=new byte[1024];
int length;
while((length=inputStream.read(b))>0){
os.write(b,0,length);
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
经测试,火狐和IE下都可以下载文件!