无法使用servletcontext从路径获取resourceasstream

v6ylcynt  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(359)

我有一个servlet来处理附件的下载。我从请求中获取附加文件的路径,并尝试使用servletcontext从中获取资源作为流,但我总是将inputstream获取为null,下面是我的doget方法:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getParameter("path");

    // Fetch File name from path and Then depending on the File extension choose
    // which ContentType using Switch structure
    Path p = Paths.get(path);
    String fileName = p.getFileName().toString();
    Optional<String> fileExtension = Optional.ofNullable(fileName).filter(f -> f.contains("."))
            .map(f -> f.substring(fileName.lastIndexOf(".") + 1));
    System.out.println("This is File Name: " + fileName);
    System.out.println("This is File Extension: " + fileExtension.orElseGet(null));

    /// Set ContentType of the HTTP header depending on the File
    /// Extensions
    switch (fileExtension.orElseGet(null).toLowerCase()) {
        case "txt":
            response.setContentType("text/plain");
            break;
        case "pdf":
            response.setContentType("application/pdf");
            break;
        case "doc":
            response.setContentType("application/msword");
            break;
        case "docx":
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            break;
        case "xlsx":
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            break;
        case "zip":
            response.setContentType("application/zip");
            break;
        case "jpeg":
            response.setContentType("image/jpeg");
            break;
        case "jpg":
            response.setContentType("image/jpeg");
            break;
        case "png":
            response.setContentType("image/png");
            break;
        case "rar":
            response.setContentType("application/x-rar-compressed");
            break;

        default:
            break;
    }

    response.setHeader("Content-disposition", "attachment; filename=" + fileName);
    //URL url = getClass().getResource(path);
    //InputStream strm=url.openStream();

     try(InputStream in = request.getServletContext().getResourceAsStream(path);
              OutputStream out = response.getOutputStream()) {

        byte[] buffer = new byte[ARBITARY_SIZE];

        int numBytesRead;
        while ((numBytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, numBytesRead);
        }
    }
}

以下是附件文件夹路径:

qgzx9mmu

qgzx9mmu1#

src/main/webapp 是servlet根文件夹,即 webapp 文件夹被复制到 .war 根目录下的文件。
这个 path 参数到 servletContext.getResourceAsStream(path) 必须是相对的,必须从 / .
所以要读那个文件,你需要 path = "/resources/Attachments/new 1.txt"

相关问题