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();
}
}