SpringMVC 使用ResponseEntity实现文件下载

下载文件:

(1)获取要下载的文件名,注意编码;

(2)在HttpHeaders中设置以下载方式打开,设置MIME类型;

(3)用FileUtils.readFileToByteArray()读取文件数据;用ResponseEntity构建返回对象

	/**
	 * Create a new {@code HttpEntity} with the given body, headers, and status code.
	 * @param body the entity body
	 * @param headers the entity headers
	 * @param status the status code
	 */
	public ResponseEntity(@Nullable T body, @Nullable MultiValueMap headers, HttpStatus status) {
		super(body, headers);
		Assert.notNull(status, "HttpStatus must not be null");
		this.status = status;
	}

HttpEntity类的源码中可以看到: 将header头转变成只能读取的对象,而不是写入的对象

	/**
	 * Create a new {@code HttpEntity} with the given body and headers.
	 * @param body the entity body
	 * @param headers the entity headers
	 */
	public HttpEntity(@Nullable T body, @Nullable MultiValueMap headers) {
		this.body = body;
		HttpHeaders tempHeaders = new HttpHeaders();
		if (headers != null) {
			tempHeaders.putAll(headers);
		}
		this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders);
	}

JSP页面:


	
		
		下载${fn:substringAfter(pic,'/') }

 

Controller代码:


	@RequestMapping("/down")
	public ResponseEntity down( HttpServletRequest request,String fileName) throws Exception {
		// D:\apache-tomcat-7.0.82\webapps\springmvc3_20180301_am
		
		//处理中文编码
		String myFileName=new String(fileName.getBytes("utf-8"),"iso-8859-1");
		
		// 获得服务器路径
		String path=request.getSession().getServletContext().getRealPath("");
		
		//获得完整的路径
		String string=path+File.separator+fileName;
		
		//输出路径
		System.out.println(string);
		
		
		//设置头信息
		HttpHeaders headers=new HttpHeaders();
		
		//设置下载的附件 (myFileName必须处理中文名称哦!)
		headers.setContentDispositionFormData("attachment", myFileName);
		
		//设置MIME类型
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
				
		//用FileUpload组件的FileUtils读取文件,并构建成ResponseEntity返回给浏览器
        //HttpStatus.CREATED是HTTP的状态码201
		return new ResponseEntity(FileUtils.readFileToByteArray(new File(string)),headers,HttpStatus.CREATED);
		
	}

显示:

SpringMVC 使用ResponseEntity实现文件下载_第1张图片

单击下载:

你可能感兴趣的:(springmvc)