spring MVC 获取servletContext,实现文件下载功能

以下是获取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。

转载于:https://blog.51cto.com/14220961/2365599

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值