1.图片的流方式显示,在controller中创建以下方法:
public void showImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("image/jpeg");
// 获取图片
File file = new File("/home/aaa.jpg");
// 创建文件输入流
FileInputStream is = new FileInputStream(file);
// 响应输出流
ServletOutputStream out = response.getOutputStream();
// 创建缓冲区
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
is.close();
out.flush();
out.close();
}
页面展示图片的时候,直接在img标签的src属性中调用这个方法:
<img src="/.../showImage.ht" />
2.文件的流方式下载:
public void download(File file, String fileName, HttpServletResponse response) throws IOException{
if(null != file){
OutputStream out =null;
InputStream in = null;
try{
in = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[in.available()];
in.read(buffer);
response.reset();
response.setHeader("content-disposition","attachment;filename=" + encodingFileName(fileName));
out = new BufferedOutputStream(response.getOutputStream());
out.write(buffer);
}catch(IOException e){
e.printStackTrace();
}finally{
if(null != in){
in.close();
}
if(null != out){
out.close();
}
}
}
}
//对文件名进行编码,解决下载文件名中文乱码的问题
private static String encodingFileName(String fileName) {
String returnFileName = "";
try {
returnFileName = URLEncoder.encode(fileName, "UTF-8");
returnFileName = StringUtils.replace(returnFileName, "+", "%20");
if (returnFileName.length() > 150) {
returnFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
returnFileName = StringUtils.replace(returnFileName, " ", "%20");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return returnFileName;
}