spring文件下载乱码

来源:互联网 发布:什么是数据采集系统 编辑:程序博客网 时间:2024/04/29 14:34

Controller.java


 @RequestMapping(value="/download")
public void downFile
(HttpServletRequest request,HttpServletResponse response) throws Exception{

String fileName=request.getParameter("fileName");
  fileName = new String(fileName.getBytes("ISO8859-1"), "utf-8");
    String realPath = request.getSession().getServletContext().getRealPath("/upload");
String filePath = realPath+File.separator+ fileName;

InputStream fis = null;
byte[] buffer = null;
try {
fis = new BufferedInputStream(new FileInputStream(filePath));
buffer = new byte[fis.available()];
fis.read(buffer);
}finally{
try {
if(fis !=null){
fis.close();
}
} catch (Exception e) {
}
}
response.setContentType("application/txt");
response.addHeader("Content-Disposition", "attachment;filename=" +  new String(fileName.getBytes(), "ISO8859-1"));
response.addHeader("Content-Length", "" + buffer.length);
OutputStream os = new BufferedOutputStream(response.getOutputStream());
os.write(buffer, 0, buffer.length);
os.flush();
os.close();
}


jsp:

对中文附件的编码:

function lookFile(){
 var id = $("#lookFile").val();
$.ajax({
 url:'${pageContext.request.contextPath}/credit/data/findAcrossById.action',
 data:{id:id},
 type:'post',
 success:function(data){
 var info = eval('('+data+')');
 var fileName =info.fileName;
 var filePath = info.filePath;

/*中文编码*/
 window.location.href="${pageContext.request.contextPath}/credit/data/download.action?

fileName="+encodeURIComponent(fileName);

 }
 });
 
  }



0 0
原创粉丝点击