1. 程式人生 > >spring MVC 獲取servletContext,實現文件下載功能

spring MVC 獲取servletContext,實現文件下載功能

項目 down min frame ping cte .get vax readfile

以下是獲取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,實現文件下載功能