写了一个执行下载的函数,@OK里面该怎么写,使用SpringMVC的时候,执行此函数可以成功下载,使用这个框架后,下载的文件大小是0
@At("/fileDownload")
@Ok("raw:stream")
public void fileDownLoad(@Param("filePath") String filePath,@Param("fileName") String fileName ,
HttpServletRequest request, HttpServletResponse response){
response.setContentType("text/html;charset=UTF-8");
try {
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
response.setContentType("application/octet-stream");
response.reset();//清除response中的缓存
//根据网络文件地址创建URL
URL url = new URL(filePath);
//获取此路径的连接
URLConnection conn = url.openConnection();
conn.connect();
Long fileLength = conn.getContentLengthLong();//获取文件大小
//设置reponse响应头,真实文件名重命名,就是在这里设置,设置编码
response.setHeader("Content-disposition",
"attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(conn.getInputStream());//构造读取流
bos = new BufferedOutputStream(response.getOutputStream());//构造输出流
byte[] buff = new byte[1024];
int bytesRead;
//每次读取缓存大小的流,写到输出流
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
response.flushBuffer();//将所有的读取的流返回给客户端
bis.close();
bos.close();
} catch (IOException e) {
e.getStackTrace();
}
}