SpringMVC基于ResponseEntity的文件下载

SpringMVC要求我们返回一个视图,否则会抛出异常
而@ResponseBody使Controller直接返回JSON数据。
而ResponseEntity 可以定义返回的HttpHeaders和HttpStatus。
在此,保存基于SpringMVC基于ResponseEntity的文件下载案例
前端很简单,一个标签而已

<a href="../emp/fileDownload.do?fileName=421785d6-d76c-46a5-86b4-2cfcb9d0e0fbbanner1.png">图片</a>

controller层

/***
	 * 文件下载
	 * 基于SpringMVC提供的ResponseEntity
	 * 以流的方式写入
	 * @param fileNamem
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/fileDownload")
	public ResponseEntity<byte[]> fileDownload(String fileName,HttpServletRequest Request) throws IOException
	{
	    //从前端获取文件名
		System.out.println(fileName);
		String path=Request.getSession().getServletContext().getRealPath("/img");
		//拼接文件路径
		String pathAndFilename=path+"\\"+fileName;
		System.out.println(pathAndFilename);
		//创建文件对象以供后面流传输
		File file=new File(pathAndFilename);
		byte body[]=null;
		ResponseEntity<byte[]> entity=null;
		try {
		    //将文件读到byte数组
			InputStream input=new FileInputStream(file);
			body=new byte[input.available()];
			input.read(body);
			//定义http头 ,状态
			HttpHeaders header=new HttpHeaders();
			header.add("Content-Disposition", "attchement;filename=" + file.getName());
			HttpStatus statusCode = HttpStatus.OK;
			//定义ResponseEntity封装返回信息
		    entity = new ResponseEntity<byte[]>(body, header, statusCode);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		
		return entity;
	}

至此,文件下载成功。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值