Spring MVC中下载文件

来源:互联网 发布:大数据平台架构师 编辑:程序博客网 时间:2024/05/17 07:49

1、简单的

直接在页面中加a标签

<a href="../resource/download/EBeansAndroid.apk"></a>
2、复杂的

写后台代码

@RequestMapping(value = "/downloadApk", method = RequestMethod.POST)@ResponseBodypublic Map<String,Object> downloadApk(HttpServletRequest request,HttpServletResponse response){//获取网站部署路径(通过ServletContext对象),用于确定下载文件位置,从而实现下载          String path = request.getRealPath("/");          //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型          response.setContentType("multipart/form-data");          //2.设置文件头:最后一个参数是设置下载文件名         response.setHeader("Content-Disposition", "attachment;fileName="+"aaa.apk");          ServletOutputStream out;          //通过文件路径获得File对象        File file = new File(path + "resource\\download\\" + "aaa.apk");          try {              FileInputStream inputStream = new FileInputStream(file);              //3.通过response获取ServletOutputStream对象(out)              out = response.getOutputStream();              int b = 0;              byte[] buffer = new byte[1024];//[]中为1024的倍数即可            while (b != -1){                 b = inputStream.read(buffer);                  //4.写到输出流(out)中                  if(b-1>=0){//防止数组越界                    out.write(buffer,0,b);                }             }              inputStream.close();              out.close();              out.flush();          } catch (IOException e) {              e.printStackTrace();          }}




0 0
原创粉丝点击