标签:dia file nload [] exce context cat private stream
以下是获取servletContext:import javax.servlet.ServletContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
/**
* ServletContext辅助类。提供springmvc获取servletContext对象及项目真实路径的静态方法
* @author Administrator
*
*/
public class ServletContextUtils {
private ServletContextUtils() {
}
/**
* 获取ServletContext对象
* @return ServletContext对象
*/
public static ServletContext getServletContext() {
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext context = webApplicationContext.getServletContext();
return context;
}
/**
* 根据folder获取文件的真实路径
* @param folder 要获取文件夹的真实路径
* @return folder的真实路径
*/
public static String getRealPath(String folder) {
ServletContext context = getServletContext();
String path = context.getRealPath(folder);
return path;
}
}
以下是文件下载代码:
@RequestMapping("/{filename}")
public ResponseEntity<byte[]> download(@PathVariable String filename) throws IOException {
ResponseEntity<byte[]> entity = null;
try {
HttpHeaders headers = new HttpHeaders();
String pathname = getFilepath(filename);
File file = new File(pathname);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
entity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
return entity;
} catch (IOException e) {
logger.error(e.getMessage());
throw e;
}
}
private String getFilepath(String filename) {
String pathname = ServletContextUtils.getRealPath("/file") + "\\" + filename + ".txt";
return pathname;
}
springmvc4 以上版本已经实现与servlet的低耦合,不知道为什么很多人写代码用的也是springMVC4或者5,仍然在使用httprequest。
spring MVC 获取servletContext,实现文件下载功能
标签:dia file nload [] exce context cat private stream
原文地址:https://blog.51cto.com/14220961/2365599