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<String, String> 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<String, String> headers) {
		this.body = body;
		HttpHeaders tempHeaders = new HttpHeaders();
		if (headers != null) {
			tempHeaders.putAll(headers);
		}
		this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders);
	}

JSP页面:

<body>
	<c:forEach items="${list}" var="pic">
		<img src="${pic }" />
		<a href="down.action?fileName=${pic }">下载${fn:substringAfter(pic,'/') }</a><p/>
	</c:forEach>
</body>

 

Controller代码:


	@RequestMapping("/down")
	public ResponseEntity<byte[]> 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<byte[]>返回给浏览器
        //HttpStatus.CREATED是HTTP的状态码201
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(string)),headers,HttpStatus.CREATED);
		
	}

显示:

单击下载:

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
实现Spring MVC的文件上传和下载功能,需要进行以下步骤: 1、引入Apache Commons FileUpload组件的依赖。在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> ``` 2、配置文件上传解析器。在Spring MVC的配置文件中,配置一个MultipartResolver的Bean用于处理文件上传请求。 3、创建文件上传的表单。在HTML表单中,设置enctype为"multipart/form-data",并添加一个文件选择框。 4、创建文件上传的控制器。在控制器中,使用MultipartFile参数接收上传的文件,并执行相应的操作,比如保存文件到指定位置。 5、创建文件下载的控制器。在控制器中,使用ResponseEntity<byte[]>对象来实现文件下载,设置相应的响应头信息,如Content-Disposition和文件名。 下面是一个示例的代码,演示了如何实现文件上传和下载: ``` // 文件上传的控制器 @Controller public class FileUploadController { @RequestMapping("/fileUpload") public String testFileUpload(MultipartFile photo, HttpSession session) throws IOException { String filename = photo.getOriginalFilename(); ServletContext servletContext = session.getServletContext(); String realPath = servletContext.getRealPath("photo"); File file = new File(realPath); if (!file.exists()) { file.mkdir(); } String finalPath = realPath + File.separator + filename; photo.transferTo(new File(finalPath)); return "success"; } } // 文件下载的控制器 @Controller public class FileDownloadController { @RequestMapping("/fileDownload") public ResponseEntity<byte[]> testFileDownload(HttpSession session) throws IOException { ServletContext servletContext = session.getServletContext(); String realPath = servletContext.getRealPath("static/img/a.jpg"); InputStream inputStream = new FileInputStream(realPath); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes); MultiValueMap<String, String> headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=a.jpg"); HttpStatus status = HttpStatus.OK; ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, status); inputStream.close(); return responseEntity; } } // 文件上传的表单 <form action="${pageContext.request.contextPath}/fileUpload" method="post" enctype="multipart/form-data"> <input type="file" name="photo" multiple> <input type="submit" value="上传"/> </form> ``` 通过以上步骤,你可以在Spring MVC中实现文件的上传和下载功能。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值