Java realizes the path acquisition mode under uploading pictures to webapp path

  • 2021-12-12 04:15:29
  • OfStack

The directory uploads the picture to the path under webapp path. The path acquisition method spring java obtains the file path under webapp

Path acquisition method under uploading pictures to webapp path

This method is obtained under the project webapp folder


String contexPath= request.getSession().getServletContext().getRealPath("/") ; 

Get the IP address port number and project name


<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

spring java Get the file path under 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");
            // Get the path of the file 
//            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(" Filename :"+downLoadName);
            response.reset();
            // Set the header information of the response ( Solutions to Chinese problems )
            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(" Error downloading picture ");
            if (input != null) {
                IOUtils.closeQuietly(input);
            }
        }
        return null;
    }

Related articles: