spring java 获取webapp下文件路径

阳光穿透心脏的1/2处 2023-06-24 04:48 109阅读 0赞
  1. @RequestMapping("/act/worldcup_schedule_time/imgdownload")
  2. @ResponseBody
  3. public String scheduleDownload(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
  4. response.setCharacterEncoding("UTF-8");
  5. String downLoadName = "worldcup.jpg";
  6. InputStream input = null;
  7. try {
  8. request.setCharacterEncoding("UTF-8");
  9. //获取文件的路径
  10. // String url = session.getServletContext().getRealPath("/") + "resources\\images\\act\\worldcup_merge\\worldcup720.png";
  11. String url = session.getServletContext().getRealPath("/") + "resources/images/act/worldcup_merge/worldcup720.png";
  12. System.out.println(url);
  13. File file = new File(url);
  14. input = FileUtils.openInputStream(file);
  15. byte[] data = IOUtils.toByteArray(input);
  16. //System.out.println("文件名:"+downLoadName);
  17. response.reset();
  18. //设置响应的报头信息(中文问题解决办法)
  19. response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(downLoadName, "UTF-8"));
  20. response.addHeader("Content-Length", "" + data.length);
  21. response.setContentType("image/png; charset=UTF-8");
  22. IOUtils.write(data, response.getOutputStream());
  23. } catch (Exception e) {
  24. logger.error("下载图片出错");
  25. if (input != null) {
  26. IOUtils.closeQuietly(input);
  27. }
  28. }
  29. return null;
  30. }

发表评论

表情:
评论列表 (有 0 条评论,109人围观)

还没有评论,来说两句吧...

相关阅读