@RequestMapping(value = "demo")
@ResponseBody
public void demo(HttpServletRequest request, HttpServletResponse response) {
String pathString = request.getSession().getServletContext().getRealPath("");
ServletOutputStream out;
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode("20170214173620719433_上传测试.txt"));
try {
File file = new File("C:\\preloan\\credit\\1/20170214173620719433_上传测试.txt");
FileInputStream inputStream = new FileInputStream(file);
//3.通过response获取ServletOutputStream对象(out)
out = response.getOutputStream();
int b = 0;
byte[] buffer = new byte[512];
while (b != -1){
b = inputStream.read(buffer);
//4.写到输出流(out)中
out.write(buffer,0,b);
}
inputStream.close();
out.close();
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
上面的还是有些问题。评论中1楼提到了。下面是整理好的 :
@RequestMapping(value = "demo")
@ResponseBody
public void demo(HttpServletRequest request, HttpServletResponse response) {
String pathString = request.getSession().getServletContext().getRealPath("/");
//设置文件ContentType类型,
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode("20170214173620719433_上传测试.txt"));
ServletOutputStream out;
//通过文件路径获得File对象
File file = new File("C:\\preloan\\credit\\1/20170214173620719433_上传测试.txt");
try {
FileInputStream inputStream = new FileInputStream(file);
//3.通过response获取ServletOutputStream对象(out)
out = response.getOutputStream();
int len = -1;
byte[] buffer = new byte[512];
while((len = inputStream.read(buffer)) != -1 ) {
out.write(buffer,0,len);
}
inputStream.close();
out.close();
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}