码上敲享录 > java入门知识分享 > java将图片输入流InputStream在浏览器下载而不是显示

java将图片输入流InputStream在浏览器下载而不是显示

上一章章节目录下一章 2021-01-11已有861人阅读 评论(0)

java将图片输入流InputStream在浏览器下载而不是显示


解决方法:

主要是这句话:response.setHeader("Content-Disposition","attachment;filename=\""+new String("gggg.jpg".getBytes("ISO8859-1"),"UTF-8")+"\"");


OutputStream os = null;

       InputStream in = null;

       try {

           Map<String, Object> resultMap = new HashMap<>();

           URL url = new URL(apiurl);

           HttpURLConnection connection = (HttpURLConnection) url.openConnection();

           connection.setConnectTimeout(5000);

           connection.setRequestMethod("GET");

           connection.connect();

           if (connection.getResponseCode() != 200) {

               resultMap.put("status", false);

               throw new Exception("网络连接异常");

           }

           in = connection.getInputStream();

           //输出

           response.reset();

           response.setCharacterEncoding("UTF-8");

           response.setContentType("image/jpeg;charset=utf-8");

           //new String 里边的是为了防止乱码

           response.setHeader("Content-Disposition","attachment;filename=\""+new String("gggg.jpg".getBytes("ISO8859-1"),"UTF-8")+"\"");

           os = response.getOutputStream();

           byte[] bt = new byte[1024];

           int len = 0;

           while ((len = in.read(bt)) != -1) {

               os.write(bt, 0, len);

           }


       } catch (Exception e) {

           e.printStackTrace();

       } finally {

           if (os != null) {

               os.flush();

               os.close();

           }

           if (in != null) {

               in.close();

           }

       }



向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交