利用 spring mvc ResponseEntity 做文件下载



controller代码:

@RequestMapping(value = "/cmpSts/{cmpId}", method = RequestMethod.GET)
	public ResponseEntity<byte[]> cmpSts(@PathVariable int cmpId,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Locale local=request.getLocale();
		String[] file = new String[]{"a.txt","a,b"};
		byte[] bs = file[1].getBytes("UTF-8");
		HttpHeaders headers = new HttpHeaders();  
	    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
	    headers.setContentDispositionFormData("attachment", new String(file[0].getBytes("UTF-8"), "ISO8859-1"));  //解决文件名中文乱码问题
		return new ResponseEntity<byte[]>(bs, headers, HttpStatus.CREATED);
	}


xml配置:

<bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<list>
			
				<bean
					class="org.springframework.http.converter.StringHttpMessageConverter">
					<property name="writeAcceptCharset" value="false" />
					<property name="supportedMediaTypes">
						<list>
							<value>text/plain;charset=UTF-8</value>
						</list>
					</property>
				</bean>
				<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> 
				<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">    
				    <property name="supportedMediaTypes">    
				        <list>    
				            <value>application/json;charset=UTF-8</value>    
				       </list>    
				    </property>  
				</bean>  
			</list>
		</property>
	</bean>



我参考文章:http://sishuok.com/forum/posts/list/5351.html



AJAX (Asynchronous JavaScript and XML) 是一种用于创建异步网页应用的技术,允许前端通过JavaScript与服务器进行非阻塞的数据交换。当涉及到从服务器下载文件时,通常会利用`ResponseEntity`这个Spring MVC的概念。 在Spring框架中,`ResponseEntity`是一个泛型类型,可以包含HTTP响应的状态码、headers以及响应体内容,包括流或者是字节数组等。要使用它来下载文件,你可以这样: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @GetMapping("/download") public ResponseEntity效验文件名及处理下载请求(@RequestParam("file") MultipartFile file) { try { // 检查文件是否有效 if (!file.isEmpty()) { String filename = extractFileName(file); Path targetPath = saveFileToFileSystem(filename, file); // 创建一个Content-Disposition header,模拟浏览器下载行为 HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", filename); // 使用 ResponseEntity.ok() 和 bytes[] 或者 FileStream来设置响应内容 return ResponseEntity.ok() .headers(headers) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(Files.readAllBytes(targetPath)); } else { return ResponseEntity.badRequest().build(); // 返回错误状态码 } } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error downloading file"); } } private String extractFileName(MultipartFile file) { return file.getOriginalFilename(); } private Path saveFileToFileSystem(String fileName, MultipartFile file) throws IOException { byte[] bytes = file.getBytes(); Path filePath = Paths.get("your/download/folder/" + fileName); Files.write(filePath, bytes); return filePath; } ``` 在这个示例中,用户提交文件到 `/download` 路径,服务端检查文件并将其保存到本地,然后返回一个`ResponseEntity`,其中包含了文件数据和适当的HTTP头部信息以启动下载。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值