springmvc实现文件下载

格陵兰鲨鱼王 1年前 ⋅ 300 阅读
  • 原来繁琐的写法
public static void downLoadFile(HttpServletResponse response, File file) {
	if (file == null || !file.exists()) {
		return; 
	} 
	OutputStream out = null; 
	try {
		response.reset(); 
		response.setContentType("application/octet-stream; charset=utf-8"); 
		response.setHeader("Content-Disposition", "attachment; filename=" + file.getName()); 
		out = response.getOutputStream(); 
		out.write(FileUtils.readFileToByteArray(file)); 
		out.flush(); 
	} catch (IOException e) {
		e.printStackTrace(); 
	} finally {
		if (out != null) {
			try {
				out.close(); 
			} catch (IOException e) {
				e.printStackTrace(); 
			} 
		} 
	} 
}
  • 使用springMvc的写法

参考文章

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

public ResponseEntity<byte[]> download(String fileName, File file) throws IOException {
	String dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1"); 
	HttpHeaders headers = new HttpHeaders(); 
	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
	headers.setContentDispositionFormData("attachment", dfileName); 
	return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); 
}

使用这种方式需要修改下application配置文件,这个是配置response的字符编码的,如果不配置,可能会出现乱码等一系列问题。

<!-- 设置json和response的字符编码 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
  <list>
	<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
	<ref bean="stringHttpMessageConverter"/>
  </list>
</property>
</bean>
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
  <list>
	<value>text/plain;charset=UTF-8</value>
  </list>
</property>
</bean>

我写的和上面的demo有一些差别。

//header头信息设置不同
headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dfileName + "\"");
//http status用的是ok
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(path)), headers, HttpStatus.OK);

如果需要抛出异常。

}catch(Exception e){
	logger.error("exportSentence error:", e);
	return new ResponseEntity<String>(new String(("导出出现异常:"+e.getMessage()).getBytes("utf-8"), "iso8859-1"), HttpStatus.OK);
}

全部评论: 0

    我有话说: