配置部分,请参考 java--文件上传
html
1.controller层代码
java
/** * 测试文件下载 * * **/ @RequestMapping(value = "/download/{fileName}", method = RequestMethod.GET) public ResultObject download(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) { System.out.println("fileName:" + fileName); ResultObject ro = customerCommentService.down(fileName,request,response); return ro; }
2.service层代码
浏览器
/** * 测试文件下载 * * **/ public ResultObject down(String fileName, HttpServletRequest request, HttpServletResponse response);
3.实现层代码app
/** * 测试文件下载 * * **/ public ResultObject down(String fileName, HttpServletRequest request, HttpServletResponse response){ ResultObject ro = new ResultObject(); //设置响应内容类型 response.setContentType("text/html;charset=utf-8"); //以下也是一种响应类型 //response.setContentType("multipart/form-data"); //设置字符编码 try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } //输入流 java.io.BufferedInputStream bis = null; //输出流 java.io.BufferedOutputStream bos = null; //得到下载文件路径 String ctxPath=request.getSession().getServletContext().getRealPath("/")+"Upload\\"; //测试文件 //fileName = "cc.txt"; //下载路径 String downLoadPath = ctxPath + fileName; System.out.println("下载文件路径:"+downLoadPath); try{ //获取文件长度 long fileLength = new File(downLoadPath).length(); //设置文件输出类型 response.setContentType("application/x-msdownload;"); response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1")); response.setHeader("Content-Length", String.valueOf(fileLength)); //从地址得到文件输入流 //这个FileInputStream后面是否是应该写成FileInputStream(new File(downLoadPath)) bis = new BufferedInputStream(new FileInputStream(downLoadPath)); //响应输入流,输出 bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; //从输入流读入到buff,从buff写入输出流 while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } //下载成功 }catch(Exception e) { e.printStackTrace(); //下载失败 }finally { if (bis != null) { try { bis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (bos != null) { try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return ro; }
4.在火狐浏览器输入测试
192.168.2.67:8080/pets/download/cc
5.出现以下截图编码
自此,结束。code