下载文件操作
java contorller代码
@RequestMapping ("/downloadZIPFile")
@ResponseBody
public void downloadZIPFile (HttpServletRequest request, HttpServletResponse response)
{
InputStream in = null;
OutputStream out = null;
try
{
request.setCharacterEncoding ("utf-8");
String filePath = request.getParameter ("filePath");//获得文件路径
String fileName = request.getParameter ("fileName");//获得要下载的文件名
File file = new File (filePath);
response.setHeader ("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding ("utf-8");//设置编码集,文件名不会发生中文乱码
response.setHeader ("Content-Disposition", "attachment;filename=" + fileName);
in = new FileInputStream (file);
out = response.getOutputStream ();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read (buffer)) > 0)
{
out.write (buffer, 0, len);
}
}
catch (Exception e)
{
if (e instanceof IOException)
{
e.printStackTrace ();
_logger.error ("文件下载发生异常!", e);
}
else if (e instanceof UnsupportedEncodingException)
{
e.printStackTrace ();
_logger.error ("设置编码格式发生异常!", e);
}
else
{
e.printStackTrace ();
_logger.error ("文件下载发生异常!", e);
}
}
finally
{
try
{
in.close ();
out.flush ();
out.close ();
}
catch (IOException e)
{
e.printStackTrace ();
}
}
}
js代码
//我这是点击datagrid的某一行,先生成文件,再下载文件的,所以有了文件名与路径;
function downloadFile(actoinURL,filePath,fileName){
var form = $("<form>");
$('body').append(form);
form.attr('style','display:none');
form.attr('target','');
form.attr('method','post');
form.attr('action',actoinURL);//下载文件的请求路径
var input1 = $('<input>');
input1.attr('type','hidden');
input1.attr('name','filePath');
input1.attr('value',filePath);
form.append(input1);
var input2 = $('<input>');
input2.attr('type','hidden');
input2.attr('name','fileName');
input2.attr('value',fileName);
form.append(input2);
form.submit();
};
对了,我在网上查过,说是ajax不能做下载文件操作!
ajax不能实现文件下载的原因:
那是因为response原因,一般请求浏览器是会处理服务器输出的response,例如生成png、文件下载等,然而ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的。文件的下载是以二进制形式进行的,虽然可以读取到返回的response,但只是读取而已,是无法执行的,说白点就是js无法调用到浏览器的下载处理机制和程序。