JQuery的ajax函数的返回类型只有xml、text、json、html等类型,没有“流”类型,所以我们要实现ajax下载,不能够使用相应的ajax函数进行文件下载。但可以用js生成一个form,用这个form提交参数,并返回“流”类型的数据。在实现过程中,页面也没有进行刷新。
前端代码:
<a href="JavaScript:downloadFile('${fileName }')">${fileName }</a><br>
function downloadFile(fileName){
var rootPath = this.getRootPath();//getRootPaht()自定义的方法,自行拼装
if(fileName){
var form=$("<form>");//定义一个form表单
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");
form.attr("action",rootPath+'/downLoadFile');
var fileInput=$("<input>");
fileInput.attr("type","hidden");
fileInput.attr("id","fileName");//设置属性的名字
fileInput.attr("name","fileName");//设置属性的名字
fileInput.attr("value",fileName);//设置属性的值
$("body").append(form);//将表单放置在web中
form.append(fileInput);
form.submit();//表单提交
//form.remove();
}
}
后台controller代码:
@RequestMapping("/downLoadFile")
@ResponseBody
public void downLoadFile(String fileName, HttpServletRequest request, HttpServletResponse response){
if(logger.isDebugEnabled()){
logger.debug("待下载文件的名称:"+fileName);
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try{
if(logger.isDebugEnabled()){
logger.debug("创建输入流读取文件...");
}
//获取输入流
bis = new BufferedInputStream(new FileInputStream(new File(GlobalConfig.getConfig(UPLOAD_FILE_PAHT), fileName)));
//获取输出流
if(logger.isDebugEnabled()){
logger.debug("创建输出流下载文件...");
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
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);
}
//刷新缓冲,写出
bos.flush();
if(logger.isDebugEnabled()){
logger.debug("文件下载成功。");
}
}catch(Exception e){
logger.error("文件下载失败"+e.getMessage());
}finally{
//关闭流
if(bis != null){
try {
bis.close();
} catch (IOException e) {
logger.error("关闭输入流失败,"+e.getMessage());
e.printStackTrace();
}
}
if(bis != null){
try {
bos.close();
} catch (IOException e) {
logger.error("关闭输出流失败,"+e.getMessage());
e.printStackTrace();
}
}
}
}
补充:如果页面需要从后台加载图片,上面的controller可以直接使用,对应的jsp只需要添加img标签即可
<img id="identityPaper2_js_showBox" title="显示图片" src="/downLoadFile/filename" style="width: 414px; height: 200px;">
img标签src属性可以直接接收图片base64数据,也可以让后台直接返回base64数据,前台将数据赋值给src属性即可:
对应后台代码调整:
@RequestMapping("/downLoadFile/{fileName}/{fileSuffix}")
@ResponseBody
public String downLoadFile(@PathVariable String fileName,@PathVariable String fileSuffix, HttpServletRequest request, HttpServletResponse response){
if(logger.isDebugEnabled()){
logger.debug("待下载文件的名称:"+fileName+",后缀:"+fileSuffix);
}
byte[] byData = new byte[]{};
try {
byData = FileUtils.readFileToByteArray(new File(GlobalConfig.getConfig(UPLOAD_FILE_PAHT),fileName+"."+fileSuffix));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String imgBase64Data = "data:image/jpg;base64,"+Base64Utils.encodeToString(byData);
return imgBase64Data;
}
前台jsp,src属性为空:
<img id="identityPaper2_js_showBox" title="显示图片" src="" style="width: 414px; height: 200px;">
处理的js:
$.get("${ctx}/agent/downLoadFile/2017041318120144084/jpg",function(data){
$("#identityPaper2_js_showBox").attr("src",data);
});
参考:http://blog.youkuaiyun.com/kane245/article/details/52766124

本文介绍了如何利用Spring MVC和Ajax技术实现在不刷新页面的情况下下载文件。由于Ajax返回类型限制,需通过创建form并提交实现。在前端,使用JQuery生成form,后台controller处理请求并返回文件流。此外,还提到了如何通过Ajax加载图片,后台可返回图片的base64数据,前端直接赋值给img标签的src属性。
609

被折叠的 条评论
为什么被折叠?



