标签:
SpirngMVC实现文件下载
@RequestMapping("/login")
public void get(HttpServletRequest request,HttpServletResponse response){
response.setContentType("text/html;chaset=utf-8");
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//定义输出流和输入流
BufferedInputStream buffinput = null;
BufferedOutputStream output = null;
String path = request.getSession().getServletContext().getRealPath("/")+"upload\\";
String down = path+request.getParameter("fileName");
try {
File f = new File(down);
//获取文件长度
long fileLength = new java.io.File(down).length();
//输出文件
buffinput = new BufferedInputStream(new FileInputStream(down));
output = new BufferedOutputStream(response.getOutputStream());
//设置头信息
response.setContentType("application/x-msdownload");
response.setHeader("content-length", String.valueOf(fileLength));
response.setHeader("content-disposition", "attachment;filename="+new String(request.getParameter("fileName").getBytes(),"ISO8859-1"));
//创建输出数组
byte[] bytelength = new byte[2048];
int byteread;
//先进行读取 在输出
while((byteread =buffinput.read(bytelength))!=-1 ){
output.write(bytelength,0,byteread);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭流
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//注释返回值 因为我们把流关了 如果有返回值 会报 链接关闭异常
//return "/MyJsp";
}
注意 下载文件一定加扩展名称 不然会报找不到文件异常
一定不要有返回值 因为 转发用到了流操作,但是我们已经把它关闭了
标签:
原文地址:http://blog.csdn.net/x329357842/article/details/51347646