spring java 獲取webapp下文件路徑


    @RequestMapping("/act/worldcup_schedule_time/imgdownload")
    @ResponseBody
    public String scheduleDownload(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        response.setCharacterEncoding("UTF-8");
        String downLoadName = "worldcup.jpg";
        InputStream input = null;
        try {
            request.setCharacterEncoding("UTF-8");
            //獲取文件的路徑
//            String url = session.getServletContext().getRealPath("/") + "resources\\images\\act\\worldcup_merge\\worldcup720.png";
            String url = session.getServletContext().getRealPath("/") + "resources/images/act/worldcup_merge/worldcup720.png";
            System.out.println(url);
            File file = new File(url);


            input = FileUtils.openInputStream(file);
            byte[] data = IOUtils.toByteArray(input);


            //System.out.println("文件名:"+downLoadName);
            response.reset();
            //設置響應的報頭信息(中文問題解決辦法)
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(downLoadName, "UTF-8"));
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("image/png; charset=UTF-8");


            IOUtils.write(data, response.getOutputStream());
        } catch (Exception e) {
            logger.error("下載圖片出錯");
            if (input != null) {
                IOUtils.closeQuietly(input);
            }
        }
        return null;
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM