文件的下载和文件的上传一样都是Web应用中一个重要的功能点。这篇“SpingMVC的文件下载”是基于以前写过的那篇“SpringMVC实现文件上传”写的,因此这里就不从头开始搭建测试项目了,直接接着上次的那个项目来进行测试,因此看这篇文章之前需要简单浏览下上次的那篇文章

注:SpringMVC实现文件上传:http://www.zifangsky.cn/406.html

(1)在UploadController.java这个controller里的upload方法中添加返回上传之后的文件的文件名:

modelAndView.addObject("picName",targetFileName);

添加之后,这个方法的完整代码如下:

@RequestMapping(value="/upload",method=RequestMethod.POST)publicModelAndViewupload(Useruser,@RequestParam("file")MultipartFiletmpFile,HttpServletRequestrequest){ModelAndViewmodelAndView=newModelAndView("fileupload");if(tmpFile!=null){//获取物理路径StringtargetDirectory=request.getSession().getServletContext().getRealPath("/uploads");StringtmpFileName=tmpFile.getOriginalFilename();//上传的文件名intdot=tmpFileName.lastIndexOf('.');Stringext="";//文件后缀名if((dot>-1)&&(dot<(tmpFileName.length()-1))){ext=tmpFileName.substring(dot+1);}//其他文件格式不处理if("png".equalsIgnoreCase(ext)||"jpg".equalsIgnoreCase(ext)||"gif".equalsIgnoreCase(ext)){//重命名上传的文件名StringtargetFileName=StringUtile.renameFileName(tmpFileName);//保存的新文件Filetarget=newFile(targetDirectory,targetFileName);try{//保存文件FileUtils.copyInputStreamToFile(tmpFile.getInputStream(),target);}catch(IOExceptione){e.printStackTrace();}Useru=newUser();u.setUserName(user.getUserName());u.setLogoSrc(request.getContextPath()+"/uploads/"+targetFileName);modelAndView.addObject("u",u);modelAndView.addObject("picName",targetFileName);}returnmodelAndView;}returnmodelAndView;}

(2)在fileupload.jsp这个文件中添加一个文件下载的超链接:

<h3>头像下载</h3><ahref="download.html?fileName=${picName}">点击下载</a>

可以看出,这里的fileName就是用的controller中的“picName”来赋值的

注:代码添加的位置如上图所示

(3)在UploadController.java中添加一个用于下载文件的方法,代码如下:

@RequestMapping(value="/download",method={RequestMethod.GET,RequestMethod.POST})publicResponseEntity<byte[]>download(@RequestParam(name="fileName")StringfileName,HttpServletRequestrequest){HttpHeadersheaders=newHttpHeaders();Patternpattern=Pattern.compile("\\w*\\.\\w+");Matchermatcher=pattern.matcher(fileName);//检查文件名中非法字符,只允许是字母、数字和下划线if(matcher.matches()){try{headers.setContentDispositionFormData("myfile",fileName);headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);//获取物理路径StringfilePath=request.getSession().getServletContext().getRealPath("/uploads");Filepic=newFile(filePath,fileName);returnnewResponseEntity<byte[]>(FileUtils.readFileToByteArray(pic),headers,HttpStatus.CREATED);}catch(Exceptione){e.printStackTrace();}}returnnull;}

注:从上面的代码可以看出,通过接收表示文件名的字符串然后跟文件的路径拼接起来,形成文件在磁盘中真实路径的File对象,最后返回文件的流并进行下载。需要注意的是,为了防止出现任意文件下载,导致下载到其他路径中的文件,因此在下载之前校验了文件名的格式。同时最后返回了一个ResponseEntity<byte[]>类型的数据,是为了在返回数据流的同时返回我们自定义的HttpHeaders和HttpStatus

(4)最后下载的效果如下: