java实现下载附件功能
Posted 爱米酱
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java实现下载附件功能相关的知识,希望对你有一定的参考价值。
前台js方法:
//下载为Excel
function downResult()
var url = $ctx/downResult.do;
var fileName = "稽核结果.xlsx";
var form = $("<form></form>").attr("action", url).attr("method", "post");
form.append($("<input></input>").attr("type", "hidden").attr("name", "fileName").attr("value", fileName));
form.appendTo(body).submit().remove();
后台controller方法(这里下载的类型是Excel,下载其他文件需要修改类型):
@ResponseBody
@RequestMapping(value="downResult.do")
public ModelAndView downResult(HttpServletRequest request,
HttpServletResponse response)throws Exception
URL url = getClass().getClassLoader().getResource("auditResult.xls");
String path = url.getPath();
//downloadFile(request,response, path, "auditResult.xlsx");
down(request,response, path, "auditResult.xlsx");
return null;
private void down(HttpServletRequest request, HttpServletResponse response, String path,String fileName) throws Exception
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
try
String agent = request.getHeader("User-Agent");
boolean isMSIE = (agent != null && (agent.indexOf("MSIE") != -1 || agent.indexOf("Trident") != -1));
if (isMSIE)
response.setHeader("Content-disposition",
"attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF8"));
else
response.setHeader("Content-disposition",
"attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setContentType("application/x-xls");
bis = new java.io.BufferedInputStream(new java.io.FileInputStream(path));
bos = new java.io.BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
bos.write(buff, 0, bytesRead);
catch(Exception e)
/*operResult.setResult("fail");
operResult.setMsg("操作失败:"+e.getMessage());*/
e.printStackTrace();
finally
if (bis != null)
bis.close();
if (bos != null)
bos.close();
以上是关于java实现下载附件功能的主要内容,如果未能解决你的问题,请参考以下文章
求C# MVC4 做的上传附件下载附件的功能 附件路径存在数据库中 附件存在项目下的uploading文件中 求源码
Java 添加下载读取PDF附件信息(基于Spire.Cloud.SDK for Java)